Dockerize Spring Boot Application (Complete Guide)

As applications move toward microservices and containerized deployments, Docker has become the go-to tool for packaging Spring Boot applications. In this complete guide, youโ€™ll learn how to dockerize Spring Boot application using best practices.

๐Ÿ“ฆ What Youโ€™ll Learn

  • What Docker is and why itโ€™s useful for Spring Boot
  • How to write a Dockerfile for your application
  • Creating .dockerignore
  • Building and running a Docker image
  • Externalizing configuration for different environments
  • Optimizing the image using JAR layering
  • Multi-stage builds (optional teaser for next blog)
Dockerize Spring Boot Application

๐Ÿงฐ Prerequisites

Make sure you have the following installed:

  • Java 17 or 21
  • Maven or Gradle
  • Docker CLI
  • A sample Spring Boot application

๐Ÿš€ Step 1: Sample Spring Boot App

Letโ€™s start with a simple Spring Boot app.
Package: com.kscodes.springboot.containers

๐Ÿ—๏ธ Step 2: Add Spring Boot Plugin (Maven)

๐Ÿ“ Step 3: Create Dockerfile

Create a file named Dockerfile in the project root.

๐Ÿ™ˆ Step 4: Add .dockerignore

To speed up Docker builds and avoid bloated image layers, create a .dockerignore:

๐Ÿ”จ Step 5: Build Docker Image

โ–ถ๏ธ Step 6: Run the Container

Navigate to http://localhost:8080 and you should see:

โš™๏ธ Step 7: Externalize Configuration

Use environment variables or mount config files:

Or mount application.properties:

๐Ÿš€ Step 8: Optimize with Layered JAR (Spring Boot 2.3+)

Spring Boot creates layered JARs to speed up Docker caching.

Run the below to inspect layers:

Then update your Dockerfile (alternate approach):

๐Ÿงช Step 9: Test with Docker Compose (Optional)

๐Ÿ›ก๏ธ Step 10: Best Practices

  • Use .dockerignore to reduce context size
  • Avoid latest tag; use semantic versions
  • Use JDK only in build stage, JRE in runtime
  • Minimize image layers
  • Keep secrets out of images

๐Ÿ“˜ Summary

In this complete guide, you learned how to dockerize a Spring Boot application using a production-ready Dockerfile, .dockerignore, and layered JAR optimization. You now understand how to build and run your app in a container, externalize configurations, and follow Docker best practices. This sets the foundation for more advanced topics like multi-stage builds, Kubernetes deployment, and cloud-native pipelines. Stay tuned for the next post in this DevOps for Spring Boot series!