Docker Compose is a tool that allows you to define and run multi-container Docker applications. With Docker Compose, you can configure your application’s services, networks, and volumes using a YAML file. This makes it easy to manage complex applications with multiple dependencies.
In this tutorial, we will explore how to use Docker Compose to containerize a Spring Boot application that interacts with a database. We'll cover the following topics:
docker-compose.yml fileBefore you begin, ensure you have the following installed on your machine:
First, let's create a simple Spring Boot application that connects to a MySQL database. You can use Spring Initializr to bootstrap your project.
Go to Spring Initializr
Select the following options:
Add the following dependencies:
Click "Generate" to download the project.
Unzip the downloaded file and import it into your favorite IDE (e.g., IntelliJ IDEA, Eclipse).
application.propertiesCreate a src/main/resources/application.properties file with the following content:
spring.datasource.url=jdbc:mysql://db:3306/demo?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
Create a new Java class src/main/java/com/example/dockercomposedemo/entity/User.java:
package com.example.dockercomposedemo.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// Getters and Setters
}
Create a new Java interface src/main/java/com/example/dockercomposedemo/repository/UserRepository.java:
package com.example.dockercomposedemo.repository;
import com.example.dockercomposedemo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}
Create a new Java class src/main/java/com/example/dockercomposedemo/controller/UserController.java:
package com.example.dockercomposedemo.controller;
import com.example.dockercomposedemo.entity.User;
import com.example.dockercomposedemo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping
public List<User> getAllUsers() {
return userRepository.findAll();
}
@PostMapping
public User createUser(@RequestBody User user) {
return userRepository.save(user);
}
}
Run your Spring Boot application. You can do this by executing the main method in DockerComposeDemoApplication.java.
docker-compose.yml FileNow, let's create a docker-compose.yml file to define our services.
docker-compose.yml at the root of your project.version: '3.8'
services:
app:
build:
context: .
dockerfile: Dockerfile
ports:
- "8080:8080"
depends_on:
- db
db:
image: mysql:5.7
environment:
MYSQL_ROOT_PASSWORD: password
MYSQL_DATABASE: demo
volumes:
- db_data:/var/lib/mysql
volumes:
db_data:
docker-compose.yml Filedb service is started before the app service.DockerfileCreate a new file named Dockerfile at the root of your project with the following content:
# Use an official OpenJDK runtime as a parent image
FROM openjdk:11-jre-slim
# Set the working directory in the container
WORKDIR /app
# Copy the built jar file from your host to your image filesystem.
COPY target/docker-compose-demo-0.0.1-SNAPSHOT.jar app.jar
# Make port 8080 available to the world outside this container
EXPOSE 8080
# Define environment variable
ENV NAME World
# Run the application
CMD ["java", "-jar", "app.jar"]
./mvnw clean package
docker-compose up --build
This command builds the images for your services if they don't exist and starts them.
Environment variables can be managed in the docker-compose.yml file under the environment section. For example, you can change the MySQL root password by modifying the MYSQL_ROOT_PASSWORD variable.
Volumes are used to persist data across container restarts. In our example, we use a named volume db_data for the MySQL database to ensure that data is not lost when the container is stopped or removed.
Once your services are up and running, you can test your application using tools like Postman or curl.
curl -X POST http://localhost:8080/users -H "Content-Type: application/json" -d '{"name":"John Doe"}'
curl http://localhost:8080/users
You should see the user you created in the response.
In this tutorial, we have learned how to use Docker Compose to containerize a Spring Boot application with multiple services. We covered setting up a simple Spring Boot application, creating a docker-compose.yml file, building and running multi-container applications, managing environment variables, and volumes. This setup allows you to easily develop, test, and deploy your applications in a consistent and reproducible environment.
By following these steps, you can containerize more complex applications with multiple dependencies using Docker Compose.