Deploy Spring Boot application and MongoDB as Containers Using Docker

Chanaka MBK
9 min readMay 20, 2022
Docker + SpringBoot + MongoDB

Hello everyone, In this blog post I’m going to describe ‘How to dockerize Springboot CRUD API with Mongo DB’.

I am going to run two docker containers. One is for the CRUD Springboot application. And the other one is for Mongo DB. Here I’m going to use a simple Employee CRUD application. Eventually, I’m going to link both containers to run the whole application.

There are 2 ways to link both containers.

  1. Run Link command manually on command prompt.
  2. Use the docker-compose.yml file.

We will see both ways later on.

Basic sketch of the proposed app

Also, this will be a bit longer than my previous posts 😃

Overview

What is Docker

Docker makes it easy to install and run software without worrying about setup or dependencies. Docker has made it straightforward for you to install and run software on any given computer not just your computer but web servers and any cloud-based computing platform.

Its primary focus is to automate the deployment of applications inside software containers and the automation of operating-system-level virtualization on Linux. It’s more lightweight than standard Containers and boots up in seconds.

What is Container

Docker container is an open-source software development platform. Its main benefit is to package applications in “containers,” allowing them to be portable among any system running the Linux operating system (OS).

In this blog, I will not be going to guide how to install docker on your PC, the benefits of Docker, and all that, So I would recommend this link Docker's official site to you guys to see the benefits of docker, installation into your PC, etc. This will take some time but it will be really helpful.

Technologies & Tools

Java 1.8
Maven 3.6.1
Springboot 2.2.7.RELEASE
log4j
Docker: version 20.10.10
Postman: version 9.19.2

Project Structure

Project Structure

Ok, let's start !!! our integration step by step.

STEP 1: Install Docker

Docker official downloads, Here you can download and install Docker on multiple platforms and just need to follow the steps according to the documentation. I used this one https://docs.docker.com/desktop/windows/install/ since I am using Windows OS.

If you can install this properly, you can verify the version using the following command.

Check Docker version

STEP 2: Create a CRUD Application

Here I’m using the Employee CRUD application and I am not going to explain those steps in this post. You guys can get a full working codebase from here.
I have added comments there for every possible step.

The following parts are the main parts of this CRUD application.

STEP 3: Set up Mongo DB Container

Here we are not going to use the ‘MongoDBConfiguration’ class as we use for the usual applications since we going to use the Mongo DB container in Docker itself.

STEP 3.1: Add Springboot dependency

Add ‘ spring-boot-starter-data-mongodb’ dependency to the POM.xml since we need this for our service layer and repository layer CRUD operations.

STEP 3.2: Get Mongo DB from Docker

Here I'm going to use the latest mongo DB version. Also, you can get your preferred version as well.

On the command line run the following command to get the latest Mongo DB.

docker pull mongo: latest

Pull Mongo DB from Docker

NOTE: If you need another version, replace this ‘latest’ with your preferred version.

Then we can verify this using the following command and it says that you have a Mongo image on your Docker instance.

docker images

Check images that are already in use

Now I’m going to run this Mongo image as a container. I am using default Mongo DB port 27017 for internal and external ports. Also my custom Mongo DB container name will be ‘employeemongodb’.

docker run -d -p 27017:27017 — name employeemongodb mongo:latest

Run as container

You can verify this after checking the containers that are already up and running.

docker ps

Checking the containers that are already up and running

Now our Mongo DB container is up and running! 👏

STEP 4: Add application.properties file

Now we need to add these Mongo DB details to our application. properties file since, going forward we are using this container as our database.

application. properties changes

You can use any customized name(employee-service-blog) for the database. But you have to use the container name(employeemongodb) that you provided earlier as a host. The port will be as default since we used the default port(27017) when running this Mongo DB container.

STEP 5: Containerize the Springboot application

STEP 5.1: Add a Docker file to the application

Now we are going to dockerize the spring boot application. For that, we have to add a file called Dockerfile (The file name should be the same) into the root folder.

Docker file

Here I’m using simple commands for this example. But when we come to the complex projects there will be more commands here. Also, I am going to build this application as a WAR file.

FROM: The FROM instruction initializes a new build stage and sets the Base Image for subsequent instructions. As such, a valid Dockerfile MUST start with a FROM instruction. The image can be any valid image. It is especially easy to start by pulling an image from the Public Repositories.
https://docs.docker.com/engine/reference/builder/#from

Here I’m going to use this ‘tomcat:8.0.51-jre8-alpine’ tomcat version to run our application. There are more options and you can choose whatever you need according to your requirement.

COPY: For simply copying files and/or directories into the build context.
https://docs.docker.com/engine/reference/builder/#copy

CMD: The main purpose of a CMD is to provide defaults for an executing container. The command will depend according to the file type that you going to build either WAR or JAR.
https://docs.docker.com/engine/reference/builder/#cmd

STEP 5.2: Build a Spring boot application to get the WAR file.

In this example, I’m building a WAR file. According to the above Docker file, my WAR file name is employee-docker-app.war. It is defined in POX.xml.

Let’s build the WAR !!

Go to the project root location and run,

mvn clean install

Build Springboot application: console output-part 1
Build Springboot application: console output -part 2

STEP 5.3: Create a Spring boot Docker image.

Here you can give any customized name to your Docker image. So my one is ‘employee

docker image build -t employee .

Create Spring boot docker image

To check the image just run,

docker images

List of available Docker images

You can see both Mongo and Spring boot images and this is already been copied into our Docker tomcat webapps folder (/usr/local/tomcat/webapps/) where we defined the above Docker file.

Now both images are set and the Mongo container is already up and running.

Now we going to the interesting part. We are going to run the spring boot app as a container and link it along with the Mongo DB container.

STEP 6: Containerize the Springboot application and link it with the Mongo DB container.

Here we have 2 options to do this job. Let's try out both ways.

1. Use one single manual command execution on the command line.

The command is,

Container link command template

Here I’m using port 8080 for both internal and external ports. You can change it according to your preference.

Run this on your console,

docker run -p 8080:8080 — name employee — link employeemongodb:mongo -d employee

Container link command

To verify, hit this command,

docker ps

List of available Docker processes (Up and running containers)

See, now we have 2 up and running containers.

Also, it is already linked, up, and running !. Do you need to confirm it?

Run the below command on your console.

docker logs employee

Docker container tomcat log: console output-part 1
Docker container tomcat log: console output-part 2

Here you can see the familiar tomcat log and it says that,

Cluster created with settings {hosts=[employeemongodb:27017] …
org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler [“http-apr-8080”] …

Before going to our testing segment I will show you the 2nd option also.

2. Use docker-compose.yml

Here what we going to do is, we going to create a file called docker-compose.yml (The name should be exact). We need to seat this under the project resource folder.

The file content is the pretty much same as a ‘Link’ command that we used earlier. But the arrangement is a bit different. It looks like this,

docker-compose.yml

Now we going to link both containers using the docker-compose.yml file. Before that, we need to stop the Mongo DB container since this docker-compose.yml file will up and link both containers together.

So you can use the following command to kill Mongo DB container process.

docker rm -f employeemongodb

Remove Docker image

So there will not be any running processes.

Before hitting the command you need to go into the ‘project resource folder’.In my case, it will be ‘D:\MY_WORK\OFFICE\RnD\JAVA\employee-docker-app\src\main\resources’.

Now we going to execute the docker-compose.yml file using this simple command.

docker-compose up

Docker container tomcat log: console output-part 1
Docker container tomcat log: console output-part 2

Same as previous you can see the tomcat log here as well.Also no need to use the ‘docker logs <container-name>’ command separately. It will show you automatically.

STEP 7: Testing

As I said at the beginning this is a bit longer but we almost covered all the important parts ✌️.

Whatever you choose to link both containers either using option 1 or 2, you should be able to access the endpoints through any 3rd party REST API tool. Here I'm using Postman.

Here are some endpoints that I have accessed through the postman.

Health Check Endpoint :

Health Check Endpoint

Create Employee :

Create Employee

Retrieve Employee By Id :

Retrieve Employee By Id

Retrieve All Employees :

Retrieve All Employees

Also, you can check and verify these stored data after logging into the MongoDB container as follows,

Step 1: Go into MongoDB container bash using,

docker exec -it employeemongodb bash

Step 2: Go into docker mongo DB using,

mongo

Go into MongoDB container bash and access mongo DB console

Step 3: See a list of databases using,

show dbs

See a list of databases

Step 4: Use relevant Mongo DB using,

use employee-service-blog

Use relevant Mongo DB

Step 5: Show a list of collections of that selected DB using,

show collections

Show a list of collections of that selected DB

Step 6: Retrieve and view data of the selected collection using,

db.employee.find()

Retrieve and view data of the selected collection

Here you can see the data that we stored through the Postman.

Here are some important Docker Keywords often we use

Important Docker Keywords

Ok ! we did 👍 all the things related to our topic including the testing.

Please visit a completed working codebase from here and I have explained every possible step in the comment section of the codebase. Please leave a comment if you have concerns or questions.

--

--

Chanaka MBK

Experienced Software Engineer with a demonstrated history of working in the information technology and services industry. Skilled in JAVA,Spring Boot, Angular.