Open In App

Docker Compose For Java Applications: Simplifying Deployment

Last Updated : 05 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Docker is an open-source platform for developers and sysadmins to build, ship, and run distributed applications. If we want to define and run more than one container then we should go for docker compose. We have to configure multiple container environments in a single file so that it simplifies the deployment process. In Java applications, Docker Compose sequencing the deployment of Java-based services, databases, and other components, ensuring consistency across various environments.

How To Create Docker Compose File?

Docker Compose YAMLml file named ‘docker-compose.yml’. This will be created inside the project root directory. In this, file we need to segregate all the services one after another and make dependency if needed. The following are a few terminologies we need to use in the docker-compose.yml file

1. Service

A service is a containerized application, or a group of containers, defined in the docker-compose.yml file. Each service represents a separate application component and can be configured independently.

2. Container

A lightweight, standalone, and executable package that includes everything needed to run a piece of software, including the code, runtime, libraries, and system tools. Docker Compose manages containers based on the services defined in the docker-compose.yml file.

3. Image

Simply image is static container or executable container. Images are used to create containers. Docker Compose can build images or use existing ones.

4. Build

The way of creating a docker image is called Build. Docker Compose can perform builds based on the configurations specified in the docker-compose.yml file.

5. Volume

A Docker volume is a way to persist data generated by and used by Docker containers. Docker Compose can be used to define volumes, allowing data to persist between container runs.

volumes:
- todo-mysql-data:/var/lib/mysql

6. Network

It creates a default network for all services defined in the docker-compose.yml file. Services within the same Docker Compose file can communicate with each other over this default network.

7. Port Mapping

Docker Compose allows us to map ports between the host machine and the containers.

ports:
- 127.0.0.1:3000:3000

8. Environment Variables

Docker Compose enables us to set environment variables for services. These variables can be used to customize the behavior of containers at runtime.

environment:
MYSQL_ROOT_PASSWORD: password
MYSQL_DATABASE: test_db

9. Docker Compose Up

The docker-compose up command is used to start the services defined in the docker-compose.yml file. It can also be used with the –build option to build images before starting containers.

docker-compose up --build

10. Docker Compose Down

The docker-compose down command is used to stop and remove the containers, networks, and volumes defined in the docker-compose.yml file. It also removes any resources created during the docker-compose up process.

docker-compose down -v

Syntax

  • The complete sample of docker-compose.yml file code with proper syntax as follows:
services:
app:
image: openjdk:17-jdk-slim
ports:
- 8000:8000
working_dir: /app
volumes:
- ./:/app
environment:
MYSQL_HOST: mysql
MYSQL_USER: root
MYSQL_PASSWORD: password
MYSQL_DB: test_db
mysql:
image: mysql:8.0
volumes:
- gfg-mysql-data:/var/lib/mysql
environment:
MYSQL_ROOT_PASSWORD: password
MYSQL_DATABASE: test_db
volumes:
gfg-mysql-data:

Build Docker Compose

The following command is used to build the docker images specified in the docker compose file. It reads the docker compose file and build the images as per specified in the docker compse file.

docker-compose build

Run Docker Compose

The following command is used to start the services specified in the docker compose file. It reads the docker compose file and start the containers based on the configurations of the services.

docker-compose run

Example Of Docker Compose With Deployment Of Java Application

Creating a simple Java application with Docker Compose. In this example, we’ll create a simple Spring Boot application. Its having get API, and it provides some sample message like “Geeks For Geeks Docker Compose Example”.

Step1: Create a Spring Boot Application

  • Create a new Spring Boot project with a basic REST endpoint. I have used spring initializr for creating spring boot project.
  • You can use any tool like Spring Initializr or your favorite IDE. Check the below screenshot for project configuration.

Creating a Spring Boot Application

  • After downloaded the project, import into your favorite IDE. Then project structure looks like below screenshot.
  • Here we need to create new files in root project directory called Dockerfile and docker-compose.yml file.

Project Structure

Step2: Create GFGController.java

  • In this controller, created sample GET API. Which returns a sample string called “Geeks For Geeks Docker Compose Example”

Java




package com.geeksforgeeks.docker.controller;
 
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
@RequestMapping("api")
public class GFGController {
 
    @GetMapping("/get-project-name")
    public String getProjectName() {
        return "Geeks For Geeks Docker Compose Example";
    }
}


Step 3: Change Port (Optional)

  • By default spring boot application run’s on 8080 port. If already any application runs on 8080 then explicitly you have to add other port.
  • You can configure port in application.properties file in application. Here i have configured 8081 as my port in application.properties file.
server.port=8081

Step 4: Build the Spring Boot Application

  • Build the project using Maven or Gradle. This will generate a JAR file in the target directory. In this example i am using maven.
  • Clean the project

Right click on project -> Run as -> maven clean

  • Build the project

Right click on project -> Run as -> maven install

  • After maven install, jar will create inside the target directory. Check in below screenshot.

target folder and jar file

Step 5: Create a Dockerfile

  • Open a file named Dockerfile in the root of your project to define the Docker image. Add below image code in it.
FROM openjdk:17-jdk-slim
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java", "-jar", "/app.jar"]

Step 6: Create Docker Compose File

  • Open a file named docker-compose.yml in the root of your project and add below code in it.
version: '3'
services:
myapp:
build: .
ports:
- "8081:8081"

Step 7: Build and Run the Docker Container

  • Open a terminal and navigate to your project directory. Run the following commands
# Build the Docker image
docker-compose build
# Run the Docker container
docker-compose up

Note: If you want to build and run your image with single command then use “docker-compose up –build”.

docker compose build

  • Now starting the containers in the docker compose file as per configured services.

Docker Compose run

Step 8: Access the Application

Open your web browser and go to “http://localhost:8081/api/get-project-name”. You should see the message “Geeks For Geeks Docker Compose Example”.

Output Of Java Application Deployment Through Docker Compose

output of spring boot docker application

Conclusion

The docker-compose.yml file easy the process of managing and deploying multiple container applications. Instead of using multiple “docker run” commands with various configurations, we can define everything in a single file. This makes it simplify to share and reproduce application stack across different environments.

Docker Compose For Java Application Deployment – FAQs

How To Scale Java Application Using Docker Compose?

By using the docker-compose up –scale command we can scale services. For example, to scale the app service to four instances, run docker-compose up –scale app=4.

How To Use Docker Compose In Production?

For production, consider using orchestrators like Kubernetes or Docker Swarm for better scalability and management.

How To Access Logs Of Services Running With Docker Compose?

Use the docker-compose logs [service] command to access logs for a specific service.

What Is The Purpose Of The depends_on key In Docker Compose?

The specified services are started before the dependent service starts. In the example, app depends on database, ensuring the database is ready before the Java application starts.

Can I Use Environment Variables In The Docker Compose file?

Yes, as shown in the above syntax. Environment variables can be set for each service.



Similar Reads

Docker Compose vs Docker Swarm
Docker is one of the most widely used container-based software on the market. Docker is an open-source platform for creating, deploying, and managing containerized applications. Docker allows us to simply bundle our apps into containers and can be deployable on any platform that supports docker software acting as a platform independent. What Is Doc
6 min read
Docker Compose Tool To Run aMulti Container Applications
The article talks about how to run multi-container applications using a single command. Docker Compose is a tool for defining and running multi-container Docker applications. With Compose, you can configure a file (YAML file) to configure your docker containers. Then Once you configured the Yaml file with a single command, you create and start all
8 min read
Docker Compose for Python Applications: A Comprehensive Guide
In the domain of present day software development, Python has arisen as a powerhouse language, leaned toward for its simplicity, readability, and flexibility. With Python, developers can make a wide cluster of uses, from web services and APIs to data handling pipelines and AI models. Notwithstanding, conveying and overseeing Python applications acr
6 min read
Docker Compose for PHP Applications: Best Practices
In the domain of web development, PHP continues to be a widely utilized programming language, fueling various websites, web applications, and APIs. As the complexity of PHP projects increases, so do the difficulties related to managing dependencies, conditions, and deployment processes, Docker Compose arises as a strong solution for addressing thes
7 min read
How To Use Docker Desktop To Deploy Docker Containerized Applications
Docker Desktop is a versatile and user-friendly tool that simplifies the deployment of Docker containerized applications on your local machine. It provides a graphical interface for managing containers, images, and volumes, making it accessible for developers and DevOps professionals. In this guide, we will walk you through the essential steps of u
7 min read
Django's Soft Delete: Simplifying Data Management
In Django, soft delete is a clever way to manage data removal. Instead of getting rid of records forever in the database, it takes a gentler approach. Here's the idea: When you want to delete certain data, you don't wipe it out completely. Instead, you place a special marker, like a flag, to show that it's not active or "deleted". This way, you hav
5 min read
Installation of Docker Compose
Docker Compose is a powerful tool that helps in simplifying the orchestration of multi-container docker applications. In this we have to configure the application services inside the Yaml file and docker-compose will read the configuration data from that Yaml script. Before Moving into the installation process, make sure that you have Docker alread
4 min read
Difference Between Docker Compose And Kubernetes
Docker Compose and Kubernetes are two prominent container orchestration solutions with distinct features and capabilities. It simplifies application stack management by allowing you to handle services, networks, and volumes in a single, understandable YAML configuration file. Kubernetes integrates nicely with other popular CI/CD technologies like J
5 min read
Docker Compose CLI Registry
Docker Compose is a powerful tool that is used to manage multi-container docker applications. Here in this guide, I will first discuss about Docker Compose CLI Registry. Then I will discuss the steps to set up the Docker Compose CLI Registry on an Ubuntu machine. After this, I will guide you through the important Docker Compose commands to manage m
4 min read
Docker Compose - How To Execute Multiple Commands?
Docker Compose is an orchestration tool that comes with Docker and enables users to run and manage multi-container applications using a YAML format file. Docker Compose comes pre-installed with Docker and does not require any additional installation or activation. In this article, we will explore what Docker Compose is. and how we can execute multi
7 min read