Spring Boot MongoDB Docker Example

Welcome to my blog post on using Spring Boot with MongoDB in a Docker container. In this post, I’ll show you how to get up and running with Spring Boot and MongoDB in a Docker container.

In this example we are going to Dockerize spring boot MongoDB application . Dockerization is one of the important aspect of development and deploying a spring based application . As a part of Devops docker is pretty much more than essential .

Docker Basic Introduction

In Short Docker is a software container, which makes it easier to deploy and run Linux applications in containers. And now that the web has made it really easy to develop and deploy your applications, many developers prefer to use the Docker instead of traditional virtual machines.

if you are new to docker , you can get started using Docker for Desktop . Learn basic Docker Commands required for a Developer.

Step by Step Guide Deploying Spring Boot with MongoDB and Docker

I’ll also show you how to use Spring Data to access your data in MongoDB and deploy using Docker. First, let’s create a Spring Boot application. If you want to create a Rest API follow the guide here .

Step 1 – Create the Spring Boot Project using Spring Initializer

I’m using the Spring Initializr to create my project. I’m going to call my project “spring-boot-mongodb-docker-example”.

Next, we need to add the spring-data-mongodb dependency to our project. This will give us access to the Spring Data MongoDB repositories.

<dependency>
  <groupId>org.springframework.data</groupId>
  <artifactId>spring-data-mongodb</artifactId>
  <version>2.2.3.RELEASE</version>
</dependency>

Now we can create a simple repository interface. This repository will be used to access data in our MongoDB database .

@Repository 
public interface PersonRepository extends MongoRepository<Person, String> {
} 

We can now inject this repository into our Spring Boot application and use it to save and retrieve data.


@SpringBootApplication
public class SpringBootMongodbDockerExampleApplication {
@Autowired
private PersonRepository personRepository;
public static void main(String[] args) {
SpringApplication.run(SpringBootMongodbDockerExampleApplication.class, args);
}
@PostConstruct
public void init() {
personRepository.save(new Person("John", "Doe"));
personRepository.save(new Person("Jane", "Doe"));
System.out.println("All persons: " + personRepository.findAll());
}
}

Now we can build our application and run it.

Step 2 : Setup Mongo DB using Docker

But before we do that, we need to start up a MongoDB database. We can do this using Docker.

First, we need to pull the MongoDB Docker image already available in docker hub .

 $ docker pull mongo 

Next, we need to start up a MongoDB container. We’ll map the MongoDB data directory to a directory on our host machine.

This will allow us to persist our data even if the MongoDB container is stopped and restarted.

$ docker run -d -p 27017:27017 -v /opt/frugalisminds/data/db:/data/db_mongo.
docker run mongo spring boot .

Here is the output and Status via docker desktop .

Lets build and run our Spring Boot application without a Docker file .

 $ ./mvnw package $ java -jar target/spring-boot-mongodb-docker-example-0.0.1-SNAPSHOT.jar 

You should see the following output:

All persons: [Person(id=5a3fa70b3b7f811b38b55f85, firstName=John, lastName=Doe), Person(id=5a3fa70b3b7f811b38b55f86, firstName=Jane, lastName=Doe)] .

Now first verify that our application is running without a docker file .

Now that we are able to get the desired output we will run the Spring Boot application using docker file .

Step 3: Create Docker Image For Spring Boot Application

Lets Create a Docker file as shown below

FROM openjdk:17
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
EXPOSE 8080
ENTRYPOINT ["java","-jar","/app.jar"]

Using Docker Compose With Spring Boot and MongoDB

We have seen in above steps we created a Spring Boot docker file and then we created a docker container to run mongo db separately . With Docker Compose we don’t have to execute docker run commands separately and manually . We will defined the steps in docker-compose.yml file and next Docker Compose will take care to install and spin up Docker Containers with Spring Boot App and Mongo DB Services .

Let’s create Docker Compose file

version: "3.7"
services:
  user_service:
    build: .
    restart: always
    ports:
      - 8080:8080
    depends_on:
      - mongo_db
  mongo_db:
    image: "mongo:4.4.3"
    restart: always
    ports:
      - 27017:27017

I will explain each section of the docker compose

The first line, “version: 3.7”, specifies the version of the compose file syntax being used.

The file contains two services: user_service and mongo_db.

The user_service service is defined with the following properties:

Services – These can be treated as components and we can have multiple componnets in a docker compose .

build– Path where source code is kept and build will start building from that path

depends_on: If my user_service is dependent on any other service , we will use depends on . In this case user_service depends on mongo_db . Without that my application wont run .

restart: always- specifies that the service should always be restarted if it fails or if the system is restarted.

ports – 8080:8080″ specifies that the service should expose port 8080 to the host machine.

The mongo_db service is defined with the following properties:

  • image: mongo:4.4.3″ specifies that the service should be created using the official MongoDB 4.4.3 image from Docker Hub.
  • restart: always” specifies that the service should always be restarted if it fails or if the system is restarted.
  • ports: – 27017:27017″ specifies that the service should expose port 27017 to the host machine.

How to Run Spring Boot Application using Docker Compose

To build and run the Docker containers defined in the Docker Compose file, follow these steps:

  1. Open your terminal or command prompt and navigate to the directory containing the docker-compose.yml file create din the above step
  2. Lets go ahead and the following command to build and start the containers:
docker-compose up --build

Leave a Comment