Spring Boot with MongoDB Using Docker Compose: A Step-by-Step Tutorial

author : Sai K

Docker Compose is a powerful tool that allows you to define and run multi-container Docker applications. In this

tutorial, we will set up a Spring Boot application that interacts with MongoDB using Docker Compose. This will

enable us to run MongoDB and our Spring Boot application in separate containers.


Prerequisites

  • JDK 17 or later

  • Maven

  • Docker and Docker Compose installed on your machine

  • IDE (IntelliJ IDEA, Eclipse, etc.)

1.1 Create a New Spring Boot Project

Use Spring Initializr to create a new project with the following configuration:

  • Project: Maven Project

  • Language: Java

  • Spring Boot: 3.2.x

  • Dependencies: Spring Web, Spring Data MongoDB

Download and unzip the project, then open it in your IDE.

Example Spring Boot Application

Create a simple Spring Boot application that interacts with RabbitMQ.

1.1 Application Class


                    package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
} 

1.2 RabbitMQ Configuration

Create a configuration class for RabbitMQ in the com.example.demo.config package.


package com.example.demo.config;

import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {

    public static final String QUEUE_NAME = "test_queue";

    @Bean
    public Queue queue() {
        return new Queue(QUEUE_NAME, false);
    }
}

1.3 RabbitMQ Producer Service

Create a service class for the RabbitMQ producer in the com.example.demo.service package.


    package com.example.demo.service;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RabbitMQProducerService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    private static final String QUEUE_NAME = "test_queue";

    public void sendMessage(String message) {
        rabbitTemplate.convertAndSend(QUEUE_NAME, message);
    }
}

1.4 RabbitMQ Consumer Service

Create a service class for the RabbitMQ consumer in the com.example.demo.service package.


    package com.example.demo.service;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

@Service
public class RabbitMQConsumerService {

    @RabbitListener(queues = RabbitMQConfig.QUEUE_NAME)
    public void receiveMessage(String message) {
        System.out.println("Received message: " + message);
    }
}

1.5 REST Controller

Create a MessageController class in the com.example.demo.controller package to send messages to RabbitMQ.


    package com.example.demo.controller;

import com.example.demo.service.RabbitMQProducerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MessageController {

    @Autowired
    private RabbitMQProducerService rabbitMQProducerService;

    @PostMapping("/send")
    public String sendMessage(@RequestParam("message") String message) {
        rabbitMQProducerService.sendMessage(message);
        return "Message sent to RabbitMQ successfully";
    }
}

1.6 application.properties Configuration

Configure your application to use RabbitMQ. In the src/main/resources directory, create or update the application.properties file.


    # src/main/resources/application.properties

spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

Step 2: Create Docker Compose Configuration

Docker Compose allows you to define and run multi-container Docker applications. You will create a docker-

compose.yml file to define the services for your Spring Boot application and RabbitMQ.


2.1 Create docker-compose.yml

Create a docker-compose.yml file in the root directory of your project.


    version: '3.8'

services:
  rabbitmq:
    image: rabbitmq:3-management
    ports:
      - "5672:5672"
      - "15672:15672"
    volumes:
      - rabbitmq_data:/var/lib/rabbitmq

  app:
    image: demo-app
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - "8080:8080"
    environment:
      SPRING_RABBITMQ_HOST: rabbitmq
      SPRING_RABBITMQ_PORT: 5672
      SPRING_RABBITMQ_USERNAME: guest
      SPRING_RABBITMQ_PASSWORD: guest
    depends_on:
      - rabbitmq

volumes:
  rabbitmq_data:

Explanation:

  • rabbitmq: Defines the RabbitMQ service.

    • image: Specifies the Docker image to use.

    • ports: Maps the container ports to the host ports.

    • volumes: Persists the RabbitMQ data.

  • app: Defines the Spring Boot application service.

    • depends_on: Ensures the RabbitMQ service is started before the Spring Boot application.

    • environment: Sets the RabbitMQ host, port, username, and password for the Spring Boot application.

    2.2 Create a Dockerfile

    Create a Dockerfile in the root directory of your project.

    
    # Use the official OpenJDK base image
    FROM openjdk:17-jdk-alpine
    
    # Set the working directory inside the container
    WORKDIR /app
    
    # Copy the built jar file into the container
    COPY target/demo-0.0.1-SNAPSHOT.jar app.jar
    
    # Expose port 8080
    EXPOSE 8080
    
    # Run the application
    ENTRYPOINT ["java", "-jar", "app.jar"]
    
                    

    Step 3: Build and Run the Application

    3.1 Build the Jar File

    Run the following command to build the jar file of your Spring Boot application:

    ./mvnw clean package

    3.2 Build and Run Docker Compose

    Run the following command to build and start the Docker Compose services:

    
                docker-compose up --build
               

    3.3 Verify the Application

    Open a web browser or a tool like Postman and navigate to the following URL to test the endpoints:

    1. Send a message to RabbitMQ:

    • URL: http://localhost:8080/send?message=HelloRabbitMQ

    • Method: POST

    Check the console output to see the consumed message:

    Received message: HelloRabbitMQ

    Conclusion

    In this tutorial, you have learned how to set up and run a Spring Boot application with RabbitMQ using

    Docker Compose. We covered:


    • Setting up a Spring Boot project with RabbitMQ.

    • Creating RabbitMQ producer and consumer services.

    • Creating a REST controller to send messages to RabbitMQ.

    • Creating a Dockerfile for the Spring Boot application.

    • Creating a docker-compose.yml file to define the services.

    • Building and running the application using Docker Compose.

    By following these steps, you can easily manage and deploy your Spring Boot application and its dependencies

    using Docker Compose, enabling seamless interaction with RabbitMQ.


    Related Spring and Spring Boot Tutorials/Guides: