codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🍃

Spring Boot

46 / 62 topics
44Docker Basics for Spring Boot Applications45Creating a Dockerfile for Spring Boot46Using Docker Compose for Multi-Container Applications
Tutorials/Spring Boot/Using Docker Compose for Multi-Container Applications
🍃Spring Boot

Using Docker Compose for Multi-Container Applications

Updated 2026-04-20
4 min read

Using Docker Compose for Multi-Container Applications

Introduction

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:

  • Setting up a simple Spring Boot application
  • Creating a docker-compose.yml file
  • Building and running multi-container applications
  • Managing environment variables and volumes

Prerequisites

Before you begin, ensure you have the following installed on your machine:

  • Docker: Install Docker
  • Docker Compose: Installed with Docker for Desktop or can be installed separately from Docker Compose

Step 1: Setting Up a Simple Spring Boot Application

First, let's create a simple Spring Boot application that connects to a MySQL database. You can use Spring Initializr to bootstrap your project.

Create a New Spring Boot Project

  1. Go to Spring Initializr

  2. Select the following options:

    • Project: Maven Project
    • Language: Java
    • Spring Boot: Latest stable version
    • Project Metadata:
      • Group: com.example
      • Artifact: docker-compose-demo
      • Name: docker-compose-demo
      • Description: Docker Compose Demo
      • Package name: com.example.dockercomposedemo
    • Packaging: Jar
    • Java: 11 or later
  3. Add the following dependencies:

    • Spring Web
    • Spring Data JPA
    • MySQL Driver
  4. Click "Generate" to download the project.

Unzip and Import the Project

Unzip the downloaded file and import it into your favorite IDE (e.g., IntelliJ IDEA, Eclipse).

Configure application.properties

Create 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 Simple Entity

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 Repository

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 Controller

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 the Application

Run your Spring Boot application. You can do this by executing the main method in DockerComposeDemoApplication.java.

Step 2: Creating a docker-compose.yml File

Now, let's create a docker-compose.yml file to define our services.

  1. Create a new file named docker-compose.yml at the root of your project.
  2. Add the following content:
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:

Explanation of the docker-compose.yml File

  • version: Specifies the version of the Docker Compose file format.
  • services: Defines the services that make up your application.
    • app: The Spring Boot application service.
      • build: Specifies the build context and Dockerfile to use.
      • ports: Maps port 8080 on the host to port 8080 in the container.
      • depends_on: Ensures that the db service is started before the app service.
    • db: The MySQL database service.
      • image: Uses the official MySQL image from Docker Hub.
      • environment: Sets environment variables for MySQL.
      • volumes: Mounts a volume to persist data.

Step 3: Building and Running Multi-Container Applications

Create a Dockerfile

Create 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"]

Build and Run Your Application

  1. Build your Spring Boot application:
./mvnw clean package
  1. Start your Docker Compose services:
docker-compose up --build

This command builds the images for your services if they don't exist and starts them.

Step 4: Managing Environment Variables and Volumes

Environment Variables

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

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.

Step 5: Testing Your Application

Once your services are up and running, you can test your application using tools like Postman or curl.

Create a User

curl -X POST http://localhost:8080/users -H "Content-Type: application/json" -d '{"name":"John Doe"}'

Get All Users

curl http://localhost:8080/users

You should see the user you created in the response.

Conclusion

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.


PreviousCreating a Dockerfile for Spring BootNext Kubernetes Basics for Spring Boot Applications

Recommended Gear

Creating a Dockerfile for Spring BootKubernetes Basics for Spring Boot Applications