DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Manage Microservices With Docker Compose
  • Spring Boot With Kubernetes
  • How To Build Self-Hosted RSS Feed Reader Using Spring Boot and Redis
  • How to Implement Two-Factor Authentication in A Spring Boot OAuth Server? Part 2: Under the Hood

Trending

  • Understanding and Mitigating IP Spoofing Attacks
  • MySQL to PostgreSQL Database Migration: A Practical Case Study
  • Java's Quiet Revolution: Thriving in the Serverless Kubernetes Era
  • How to Build Local LLM RAG Apps With Ollama, DeepSeek-R1, and SingleStore
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring Boot: Run and Build in Docker

Spring Boot: Run and Build in Docker

We take a look at how to create Java and Spring Boot-based applications in a Docker container. It's gonna be a whale of a time!

By 
Pavel Sklenar user avatar
Pavel Sklenar
·
Feb. 20, 19 · Tutorial
Likes (29)
Comment
Save
Tweet
Share
52.2K Views

Join the DZone community and get the full member experience.

Join For Free

There are a lot of guides on “Docker for Java developers,” but most of them do not take care of small and efficient Docker images.

I have combined many resources on how to make a simple and fast Docker image containing any Spring Boot-like application.

My goals:

  • Create a single and portable Dockerfile (as general as possible).
  • Make Maven build inside Docker (no need to have Maven locally).
  • Don’t download any Maven dependencies repeatedly, if no changes in pom.xml (rebuilding image as fast as possible).
  • The final Docker image should contain only application itself (no source codes, no Maven dependencies required by Maven build, etc.)
  • The final image should be as small as possible (no full JDK required).
  • The application inside Docker should remain configurable as much as possible (with all Spring Boot configuration options).
  • Possibility to enable debugging (on demand).
  • Possibility to see log files.

The final image is designed for development purposes, but it does not contain any no-go production parts and it is fully configurable.

To see a working example, see  my GitHub project.

To fulfill a single portable Dockerfile requirement, I need to use Docker multi-stage builds.

It will have two main parts (stages):

  • The building part.
  • The runtime part.

The Building Part of the Dockerfile


### BUILD image
FROM maven:3-jdk-11 as builder
# create app folder for sources
RUN mkdir -p /build
WORKDIR /build
COPY pom.xml /build
#Download all required dependencies into one layer
RUN mvn -B dependency:resolve dependency:resolve-plugins
#Copy source code
COPY src /build/src
# Build application
RUN mvn package

I have started from the official Maven image, so you may change this as you wish. The most interesting part is this:

RUN mvn -B dependency:resolve dependency:resolve-plugins

It downloads all dependencies required either by your application or by plugins called during a build process. Then all dependencies are a part of one layer. That layer does not change until any changes are found in the pom.xml file. 

So the rebuilding is very fast and does not include downloading all the dependencies again and again.

The second option, how to download required dependencies, comes from the official Docker Maven site (when you have some problems with the previous variant):

RUN mvn -B -e -C -T 1C org.apache.maven.plugins:maven-dependency-plugin:3.0.2:go-offline

How to Customize Maven Settings

There are many situations where you need to change a default Maven setting for your customized build. To do that, you need to copy your settings.xml file into the image before you provide the builder image definition, For example:

FROM maven:3-jdk-11 as builder
#Copy Custom Maven settings
COPY settings.xml /root/.m2/

The Runtime Part of the Dockerfile

FROM openjdk:11-slim as runtime
EXPOSE 8080
#Set app home folder
ENV APP_HOME /app
#Possibility to set JVM options (https://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html)
ENV JAVA_OPTS=""

#Create base app folder
RUN mkdir $APP_HOME
#Create folder to save configuration files
RUN mkdir $APP_HOME/config
#Create folder with application logs
RUN mkdir $APP_HOME/log

VOLUME $APP_HOME/log
VOLUME $APP_HOME/config

WORKDIR $APP_HOME
#Copy executable jar file from the builder image
COPY --from=builder /build/target/*.jar app.jar

ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar app.jar" ]
#Second option using shell form:
#ENTRYPOINT exec java $JAVA_OPTS -jar app.jar $0 $@

The runtime part starts with some necessary steps, i.e. exposing ports, setting up environments, and creating some useful folders. The most interesting part is related to copying a previously created jar file into our new image:

#Copy executable jar file from the builder image
COPY --from=builder /build/target/*.jar app.jar

I am copying from the builder image, see the param –from. For more information about copying files from other images, see the Docker documentation page. 

As for the Spring Boot application, the created jar file is executable, so it is possible to run our application with the single command:

ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar app.jar" ]

To reduce Tomcat startup time there is a system property pointing to /dev/urandom.

There are other options for runing a Spring Boot application inside Docker. For more info, visit the official Spring guide.

How to Build and Run Spring Boot Application in Docker in One Step

docker build -t <image_tag> . &amp;&amp; docker run -p 8080:8080 <image_tag>

The above command will build your application with Maven and start it without any delay. This is the simplest way without any customizations. The file may come with some specific requirements, so here’s a couple of them.

Now you can visit the URL to get response from my GitHub example:

http://localhost:8081/customer/10

How to Debug?

My example uses Java 11, so there are some JVM options to enable debug mode:

docker build -t <image_tag> . && docker run -p 8080:8080 -p 5005:5005 --env JAVA_OPTS=-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005 <image_tag>

You need to add the Docker environment variable, JAVA_OPTS, with JVM options and map the internal debugging port to the outside of the container: -p 5005:5005.

For Java 5-8 containers, use this JAVA_OPTS parameter:

JAVA_OPTS=-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005

How to Setup Logging

The runtime container contains a folder called app/app/log with all the log files. This path could be easily mounted into your host:

docker build -t <image_tag> . && docker run -p 8080:8080 -v /opt/spring-boot/test/log:/app/log <image_tag>

How to Change the Application Configuration

The jar file contains the default configuration. To selectively override those values, you have many options. I will show you some of them.

Please note that all of the configurations are possible when using the exec form of the ENTRYPOINT. When using the shell form of the ENTRYPOINT, you need to pass all command line arguments manually:

ENTRYPOINT exec java $JAVA_OPTS -jar app.jar $0 $@

Command Line Arguments

Spring Boot automatically accepts all command line arguments and these arguments are passed into the run command inside Docker:

docker build -t <image_tag> . && docker run -p 8080:8080 <image_tag> --logging.level.org.springframework=debug

System Properties

A similar way is using regular system properties:

docker build -t <image_tag> . && docker run -p 8080:8080 --env JAVA_OPTS=-Dlogging.level.org.springframework=DEBUG <image_tag>

Environment Variables

You may use environment variables instead of system properties. Most operating systems do not allow for period-separated key names, but you can use underscores instead (for example,  SPRING_CONFIG_NAME  instead of  spring.config.name ). Check the documentation page for more information.

docker build -t <image_tag> . && docker run -p 8080:8080 --env LOGGING_LEVEL_ORG_SPRINGFRAMEWORK=DEBUG <image_tag>

Mount Your Own Configuration File

You may have noticed that there is a VOLUME command for mounting a configuration folder:

docker build -t <image_tag> . && docker run -p 8080:8080 -v /opt/spring-boot/test/config:/app/config:ro <image_tag>

So your local folder /opt/spring-boot/test/config should contain the file application.properties. This is the default configuration file name and can be easily changed by setting the property spring.config.name.

That's all for this post, but your requirements may vary in many ways. I tried to solve some of the most important conditions Java developers using Docker. 

As mentioned above, see the project example on  my GitHub for all of the code.

Some interesting links:

  • The official Spring Boot in Docker guide
  • Externalized Configuration in Spring Boot
  • Docker Multi-stage builds
  • OpenJDK Docker images
  • Maven Docker images
Spring Framework Docker (software) Spring Boot Build (game engine)

Published at DZone with permission of Pavel Sklenar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Manage Microservices With Docker Compose
  • Spring Boot With Kubernetes
  • How To Build Self-Hosted RSS Feed Reader Using Spring Boot and Redis
  • How to Implement Two-Factor Authentication in A Spring Boot OAuth Server? Part 2: Under the Hood

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!