Run a Spring Boot app in a Docker container

featured image

For development purposes, you can easily run Spring Boot apps with Docker Compose.

Dockerize Spring Boot on development environment

We’re going to start a Spring Boot application written in Java 11 (OpenJDK) in a container. Additionally, you can see the example spring-boot-log4j-2-scaffolding project for more details.

Build a Docker image for your app

Firstly, we have to create a JAR file for our project. Run the following command in the project’s directory:

As a result, Maven builds the ready to use JAR file, as stated in docs:

The package goal will compile your Java code, run any tests, and finish by packaging the code up in a JAR file within the target directory.

https://spring.io/guides/gs/maven/

Secondly, create the Dockerfile file and copy the following code:

Make sure, that the ARG will contain the proper target path. If your Dockerfile isn’t in the same directory as the target folder, the build process for a service called ‘app’ will exit with the following error:

You can fix it in two different ways:

  • provide an absolute path to the target;
  • move Dockerfile so it’s in the same directory as target.

Run Spring Boot with Docker Compose

Create the docker-compose.yml file and put the following code in it:

  • Our build context (Dockerfile) is in the same folder as the compose file. Therefore we specify the location just with the ./ path.
  • We keep using the default 8080 port. As a result we still can access our app by visiting http://localhost:8080/.
  • It’s likely that we want to enable communication between our Spring Boot app and other services that might be specified in the docker-compose.yml file. Thus, we define a network that they can share.

Finally, we can run the application. Remember to use the name of your service instead of my name – app:

In case of any changes, rebuild the image:

In the end, you can verify whether the service was started by running in the console:

The output should be similar to the one presented in the screenshot below:

Spring Boot run with Docker

In addition, you can find the code responsible for building and running a Docker container with my Spring Boot project in the commit e2e4862fe782c5f3ac089ebcdf6521881f0794df.

Learn more on building Spring Boot apps with Docker

Photo by Retha Ferguson from Pexels

Leave a Reply

Your email address will not be published.