0
0
SpringbootHow-ToBeginner · 4 min read

How to Use Docker with Spring Boot: Simple Guide

To use Docker with Spring Boot, create a Dockerfile that packages your Spring Boot jar into a container image. Then build the image with docker build and run it using docker run to deploy your app in a container.
📐

Syntax

A typical Dockerfile for Spring Boot has these parts:

  • Base image: Usually an OpenJDK image to run Java apps.
  • Copy jar: Copy your built Spring Boot jar into the image.
  • Expose port: Open the port your app listens on (default 8080).
  • Run command: Command to start the Spring Boot app with java -jar.
dockerfile
FROM eclipse-temurin:17-jdk-alpine
COPY target/myapp.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "/app.jar"]
💻

Example

This example shows how to containerize a Spring Boot app named myapp.jar. It uses OpenJDK 17 on Alpine Linux for a small image size. After building the image, you can run it and access the app on port 8080.

dockerfile
FROM eclipse-temurin:17-jdk-alpine
COPY target/myapp.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "/app.jar"]
Output
Successfully built image with your Spring Boot app running on port 8080
⚠️

Common Pitfalls

Common mistakes when using Docker with Spring Boot include:

  • Not building the Spring Boot jar before creating the Docker image.
  • Forgetting to expose the correct port in the Dockerfile.
  • Using a base image without Java installed.
  • Running the container without mapping ports to the host.

Always build your jar with ./mvnw clean package or ./gradlew build before building the Docker image.

dockerfile
### Wrong Dockerfile (missing jar build and wrong base image)
FROM alpine
COPY target/myapp.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "/app.jar"]

### Correct Dockerfile
FROM eclipse-temurin:17-jdk-alpine
COPY target/myapp.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "/app.jar"]
📊

Quick Reference

Tips for using Docker with Spring Boot:

  • Build your Spring Boot jar before Docker image creation.
  • Use a lightweight Java base image like eclipse-temurin:17-jdk-alpine.
  • Expose the port your app uses (default 8080).
  • Run the container with port mapping: docker run -p 8080:8080 your-image.
  • Use .dockerignore to exclude unnecessary files from the image.

Key Takeaways

Create a Dockerfile that copies your Spring Boot jar and runs it with Java.
Use a Java base image like eclipse-temurin:17-jdk-alpine for small, efficient containers.
Build your Spring Boot jar before building the Docker image to avoid errors.
Expose and map the correct port to access your app outside the container.
Avoid common mistakes like missing jar builds or wrong base images.