HelloKoding

Practical coding guides

Spring Boot with Docker Compose and MongoDB

This tutorial walks you through the steps of creating a simple Spring Boot web application with NGINX and MongoDB running inside Docker containers

What you’ll need

  • Docker CE

Stack

  • Docker
  • Spring Boot
  • MongoDB
  • NGINX
  • Maven

Init project structure and dependencies

Project structure

├── app
│   ├── src
│   │   └── main
│   │       ├── java
│   │       │   └── com
│   │       │       └── hellokoding
│   │       │           └── springboot
│   │       │               ├── IndexController.java
│   │       │               └── WebApplication.java
│   │       └── resources
│   │           ├── static
│   │           │   ├── css
│   │           │   │   └── main.css
│   │           │   └── js
│   │           │       └── main.js
│   │           ├── templates
│   │           │   └── index.ftl
│   │           └── application.properties
│   ├── Dockerfile
│   └── pom.xml
├── nginx
│   └── conf.d
│       └── app.conf
└── docker-compose.yaml

Application dependencies

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.hellokoding.springboot</groupId>
    <artifactId>dockercompose-springboot-mongodb</artifactId>
    <description>dockercompose-springboot-mongodb</description>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.7.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Define Controller, View Template and Config

Controller

IndexController.java

package com.hellokoding.springboot;

import com.mongodb.MongoClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.logging.Level;
import java.util.logging.Logger;

@Controller
@RequestMapping("/")
public class IndexController {
    private final Logger logger = Logger.getLogger(this.getClass().getName());

    @Autowired
    MongoClient mongoClient;

    @GetMapping
    public String index(Model model) {
        logger.log(Level.INFO, "First database name: {0}", mongoClient.listDatabaseNames().first());
        return "index";
    }
}

The MongoClient bean is auto-configured and provided by Spring Boot

FreeMarker View template

index.ftl

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Docker Compose with Spring Boot, MongoDB, NGINX</title>
</head>
<body>
    <h1>Docker Compose with Spring Boot, MongoDB, NGINX</h1>
    <p></p>
</body>
</html>

Application Configuration

application.properties

spring.freemarker.template-loader-path: classpath:/templates
spring.freemarker.suffix: .ftl

spring.data.mongodb.host=hk-mongodb

spring.data.mongodb.host is a common property of Spring Boot auto-configuration for MongoDB

hk-mongodb is the Docker Compose service name of MongoDB as we are going to run this Spring Boot application and MongoDB server inside Docker containers. You can find below the docker-compose.yaml file for more details

WebApplication.java

package com.hellokoding.springboot;

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

@SpringBootApplication
public class WebApplication {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(WebApplication.class, args);
    }
}

Dockerize

Dockerfile of Spring Boot web application

Dockerfile

FROM maven:3.5-jdk-8

NGINX config file

app.conf

server {
    listen 80;
    charset utf-8;
    access_log off;

    location / {
        proxy_pass http://app:8080;
        proxy_set_header Host $host:$server_port;
        proxy_set_header X-Forwarded-Host $server_name;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    location /static {
        access_log   off;
        expires      30d;

        alias /app/static;
    }
}

Docker Compose

docker-compose.yaml

version: '3'
services:
  hk-nginx:
   container_name: hk-nginx
   image: nginx:1.13
   restart: always
   ports:
   - 80:80
   - 443:443
   volumes:
   - ./nginx/conf.d:/etc/nginx/conf.d
   depends_on:
   - app

  hk-mongodb:
    container_name: hk-mongodb
    image: mongo:3.6
    restart: always
    environment:
      - MONGO_DATA_DIR=/data/db
      - MONGO_LOG_DIR=/dev/null
    ports:
      - 27017:27017
    command: mongod --smallfiles --logpath=/dev/null # --quiet

  app:
    build: ./app
    working_dir: /app
    volumes:
      - ./app:/app
      - ~/.m2:/root/.m2
    expose:
      - 8080
    command: mvn clean spring-boot:run
    depends_on:
      - hk-mongodb

Run and Test

  • Run command docker-compose up
  • Access to http://localhost

Source code

https://github.com/hellokoding/hellokoding-courses/blob/master/docker-examples/dockercompose-springboot-mongodb-nginx/app

Follow HelloKoding