Docker: Running a Spring Boot based app using docker-compose

Docker Compose gives us the ability to define services,  ports, volumes, and networks in a single file.  This  file provides a convenient and unified view into what would otherwise be a long list of docker commands.

In this article, you will run the Spring Boot based spring-music app in a Docker container using docker-compose.

Prerequisites

In my last article, I showed how to build and run the spring-music web application in a Docker container (without docker-compose).

In order to move on, run all the instructions in my previous article on Docker which includes installing Java and creating the executable jar which is mandatory for the upcoming steps.

Build Docker Image

Per the last article, we already have an executable jar ready at “build/libs/spring-music.jar”.  But instead of using docker directly, we want to build  using docker-composer.  The file that controls this build is “docker-compose.yml“.

version '3.6'

services:
  my-springmusic:
    image: my-springmusic
    build: .
    ports:
      - 8080:8080
    environment:
      - example=my value 
    volumes:
      - javatmp:/tmp

volumes:
  # default dir /var/lib/docker/volumes
  javatmp:

So instead of needing to specify the port, environment variables, or volumes on the command line using long docker commands, we can now instead use this file to capture all those details.  Then build using:

$ sudo docker-compose build

Validate the build with:

$ sudo docker images

which should show a list containing ‘my-springmusic’.

Run Docker container

The last step is to use the Docker image to instantiate a container.  The file contains all the port, env, volume, and network information, so all it takes is a command like below:

$ sudo docker-compose up

Validate Application

Pointing your browser at http://127.0.0.1:8080 should show you the web interface similar to below with a listing of albums.

 

Further Reading

If you want to run this same project but with an external MongoDB persistence store, then read my article here.

 

 

REFERENCES

https://docs.docker.com/compose/compose-file/

https://docs.docker.com/network/links/ (docker links now deprecated in favor of user defined networks)

http://www.ameyalokare.com/docker/2017/09/14/docker-migrating-legacy-links.html

https://stevescodingblog.co.uk/docker-2-composing-with-docker-compose/