Docker Compose: MongoDB and Spring Boot example

Docker provides lightweight containers to run services in isolation from our infrastructure so we can deliver software quickly. In this tutorial, I will show you how to dockerize Spring Boot and MongoDB example using Docker Compose.

Related Posts:
Spring Boot and MongoDB CRUD example
Spring Boot Reactive + MongoDB example
Spring Boot, Spring Security, MongoDB: JWT Authentication example
– Documentation: Spring Boot Swagger 3 example
– Caching: Spring Boot Redis Cache example


Assume that we have a Spring Boot Application working with MongoDB database.
The problem is to containerize a system that requires more than one Docker container:

  • Spring Boot for Rest API
  • MongoDB for database

Docker Compose helps us setup the system more easily and efficiently than with only Docker. We’re gonna following these steps:

  • Create Spring Boot App working with MongoDB database.
  • Create Dockerfile for Spring Boot App.
  • Write Docker Compose configurations in YAML file.
  • Set Spring Boot Docker Compose Environment variables.
  • Run the system.

Directory Structure:


Create Spring Boot App

You can read and get Github source code from one of following tutorials:
Spring Boot and MongoDB CRUD example
Spring Boot Reactive + MongoDB example
Spring Boot, Spring Security, MongoDB: JWT Authentication example

Using the code base above, we put the Spring Boot project in bezkoder-app folder without the need of resources/ It is because Environment variables will be exported to .env file.

Create Dockerfile for Spring Boot App

Dockerfile defines a list of commands that Docker uses for setting up the Spring Boot application environment. So we put the file in bezkoder-app folder.

Because we will use Docker Compose, we won’t define all the configuration commands in this Dockerfile.


# FROM maven:3.8.2-jdk-8 # for Java 8
FROM maven:3.8.5-openjdk-17

WORKDIR /bezkoder-app
COPY . .
RUN mvn clean install

CMD mvn spring-boot:run

Let me explain some points:

  • FROM: install the image of the Maven – JDK version.
  • WORKDIR: path of the working directory.
  • COPY: copy all the files inside the project directory to the container.
  • RUN: execute a command-line inside the container: mvn clean install to install the dependencies in pom.xml.
  • CMD: run script mvn spring-boot:run after the image is built.

Write Docker Compose configurations

On the root of the project directory, we’re gonna create the docker-compose.yml file. Follow version 3 syntax defined by Docker:

version: "3.8"

    image: mongo:5.0.2
    restart: unless-stopped
    env_file: ./.env
      - db:/data/db
      - mongo_db
    build: ./bezkoder-app
    restart: on-failure
    env_file: ./.env
          "" : "mongodb://$MONGODB_USER:$MONGODB_PASSWORD@mongo_db:$MONGODB_DOCKER_PORT/$MONGODB_DATABASE?authSource=admin"
      - .m2:/root/.m2
    stdin_open: true
    tty: true



  • image: official Docker image
  • restart: configure the restart policy
  • env_file: specify our .env path that we will create later
  • environment: provide setting using environment variables
  • ports: specify ports will be used
  • volumes: map volume folders


  • depends_on: dependency order, mongo_db is started before app
  • build: configuration options that are applied at build time that we defined in the Dockerfile with relative path
  • environment: environmental variables that Spring Boot application uses
  • stdin_open and tty: keep open the terminal after building container

You should note that the host port (LOCAL_PORT) and the container port (DOCKER_PORT) is different. Networked service-to-service communication uses the container port, and the outside uses the host port.

Docker Compose Environment variables

In the service configuration, we used environmental variables defined inside the .env file. Now we start writing it.




Run the Spring Boot microservice with Docker Compose

We can easily run the whole with only a single command:
docker compose up

Docker will pull the MongoDB and Maven images (if our machine does not have it before).

The services can be run on the background with command:
docker compose up -d

$ docker compose up -d
[+] Running 11/11
 ✔ mongodb 10 layers [⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿]      0B/0B      Pulled                                                                                                                                                    
   ✔ 35807b77a593 Pull complete                                                                                                                                                                                     
   ✔ 664b0ebdcc07 Pull complete                                                                                                                                                                    
   ✔ d598f4d3c081 Pull complete                                                                                                                                                                      
   ✔ 291455135b00 Pull complete                                                                                                                                                              
   ✔ b46409342f13 Pull complete                                                                                                                                                                      
   ✔ ff2b9c6e6f3a Pull complete                                                                                                                                                              
   ✔ 149f6335fc27 Pull complete                                                                                                                                                                    
   ✔ baeb6f3bec76 Pull complete                                                                                                                                                                        
   ✔ 8617caab2de5 Pull complete                                                                                                                                                                       
   ✔ 067d70de7828 Pull complete                                                                                                                                                             
[+] Building 87.9s (9/9) FINISHED                                                                                                                                                                               docker:default
 => [app internal] load .dockerignore                                                                                                                                                         
 => => transferring context: 2B                                                                                                                                                                        
 => [app internal] load build definition from Dockerfile                                                                                                                                                
 => => transferring dockerfile: 238B                                                                                                                                                        
 => [app internal] load metadata for                                                                                                                            
 => [app 1/4] FROM                                                                     
 => [app internal] load build context                                                                                                                                                                            
 => => transferring context: 31.57kB                                                                                                                                                             
 => CACHED [app 2/4] WORKDIR /bezkoder-app                                                                                                                                                           
 => [app 3/4] COPY . .                                                                                                                                                                         
 => [app 4/4] RUN mvn clean install                                                                                                                                                                  
 => [app] exporting to image                                                                                                                                                                                 
 => => exporting layers                                                                                                                                                                              
 => => writing image sha256:c2f10209e87c064f039545b2e6812c9c15a405120d595d7e1ff888bd3cce267f                                                                                                            
 => => naming to                                                                                                                                          
[+] Running 4/4                                                                                                                                                                                                                
 ✔ Network spring-boot-mongodb_default      Created                                                                                                                                            
 ✔ Volume "spring-boot-mongodb_db"          Created                                                                                                                                                     
 ✔ Container spring-boot-mongodb-mongodb-1  Started                                                                                                                                                  
 ✔ Container spring-boot-mongodb-app-1      Started

Now you can check the current working containers:

$ docker ps
CONTAINER ID   IMAGE                     COMMAND                  CREATED         STATUS         PORTS                                         NAMES
88af893b2a53   spring-boot-mongodb-app   "/usr/local/bin/mvn-…"   2 minutes ago   Up 2 minutes>8080/tcp, :::6868->8080/tcp     spring-boot-mongodb-app-1
4ef8f9734878   mongo:5.0.2               "docker-entrypoint.s…"   2 minutes ago   Up 2 minutes>27017/tcp, :::7017->27017/tcp   spring-boot-mongodb-mongodb-1

And Docker images:

$ docker images
REPOSITORY                 TAG       IMAGE ID       CREATED         SIZE
spring-boot-mongodb-app    latest    c2f10209e87c   2 minutes ago   912MB
mongo                      5.0.2     0bcbeb494bed   2 years ago     684MB

Send a HTTP request to the Spring Boot – MongoDB system:


Check MongoDB Database:

$ docker exec -ti spring-boot-mongodb-mongodb-1 /bin/bash
root@2d71784ae3a9:/# mongo -u root -p 123456 --authenticationDatabase admin
MongoDB shell version v5.0.2
connecting to: mongodb://
Implicit session: session { "id" : UUID("742022a6-49ed-42dd-9a53-0fd156f234ec") }
MongoDB server version: 5.0.2

> show dbs
admin        0.000GB
bezkoder_db  0.000GB
config       0.000GB
local        0.000GB
> use bezkoder_db
switched to db bezkoder_db
> show collections
> db.tutorials.find()
{ "_id" : ObjectId("6541dff55fa4083bdb3d0422"), "title" : "Docker Compose MongoDB Spring Boot", "description" : "Tut#1 Description", "published" : false, "_class" : "" }

Stop the Application

Stopping all the running containers is also simple with a single command:
docker compose down

$ docker compose down
 ✔ Container spring-boot-mongodb-app-1       Removed
 ✔ Container spring-boot-mongodb-mongo_db-1  Removed
 ✔ Network spring-boot-mongodb_default       Removed    

If you need to stop and remove all containers, networks, and all images used by any service in docker-compose.yml file, use the command:
docker compose down --rmi all

$ docker compose down --rmi all
[+] Running 5/5
 ✔ Container spring-boot-mongodb-app-1       Removed
 ✔ Container spring-boot-mongodb-mongo_db-1  Removed
 ✔ Image spring-boot-mongodb-app:latest      Removed
 ✔ Image mongo:5.0.2                         Removed
 ✔ Network spring-boot-mongodb_default       Removed     


Today we’ve successfully created Docker Compose file for MongoDB and Spring Boot example. Now we can connect Spring Boot to MongoDB with Docker on a very simple way: docker-compose.yml.

You can apply this way to one of following project:
Spring Boot and MongoDB CRUD example
Spring Boot Reactive + MongoDB example
Spring Boot, Spring Security, MongoDB: JWT Authentication example

Happy Learning! See you again.

Source Code

The source code for this tutorial can be found at Github.

Documentation: Spring Boot + Swagger 3 example (with OpenAPI 3)
Caching: Spring Boot Redis Cache example

You can deploy the container on Digital Ocean with very small budget: 5$/month.
Using referral link below, you will have 200$ in credit over 60 days. After that, you can stop the VPS with no cost.

DigitalOcean Referral Badge