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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads