How to Use Docker Compose with Spring Boot
To use
docker-compose with a Spring Boot app, create a Dockerfile to containerize your app, then define services in a docker-compose.yml file specifying the image build and ports. Run docker-compose up to start your Spring Boot app inside a Docker container easily.Syntax
The docker-compose.yml file defines services, networks, and volumes for your app. Key parts include:
- version: Compose file format version.
- services: Defines containers to run.
- build: Path to Dockerfile to build the image.
- ports: Maps container ports to host ports.
The Dockerfile describes how to build your Spring Boot app image, usually starting from a Java base image, copying the jar, and setting the startup command.
yaml
version: '3.8' services: springboot-app: build: . ports: - "8080:8080"
Example
This example shows a simple Spring Boot app containerized with a Dockerfile and run using docker-compose.
plaintext
### Dockerfile FROM eclipse-temurin:17-jdk-alpine ARG JAR_FILE=target/*.jar COPY ${JAR_FILE} app.jar ENTRYPOINT ["java","-jar","/app.jar"] --- ### docker-compose.yml version: '3.8' services: springboot-app: build: . ports: - "8080:8080"
Output
Starting springboot-app ... done
Attaching to springboot-app
springboot-app | 2024-06-01 12:00:00.000 INFO 1 --- [ main] com.example.Application : Started Application in 3.5 seconds (JVM running for 4.0)
Common Pitfalls
Common mistakes include:
- Not exposing the correct port in
docker-compose.yml(e.g., mapping wrong ports). - Forgetting to build the jar before running
docker-compose. - Using an incorrect base image in the Dockerfile that doesn't support your Java version.
- Not setting the correct
ENTRYPOINTorCMDto start the Spring Boot app.
yaml
### Wrong port mapping example version: '3.8' services: springboot-app: build: . ports: - "9090:8080" # Host port 9090 mapped to container 8080 ### Correct port mapping example version: '3.8' services: springboot-app: build: . ports: - "8080:8080"
Quick Reference
Tips for using Docker Compose with Spring Boot:
- Always build your jar with
./mvnw clean packagebefore building the Docker image. - Use a lightweight Java base image like
eclipse-temurin:17-jdk-alpinefor smaller images. - Map container port 8080 to a host port to access your app in the browser.
- Use
docker-compose up --buildto rebuild images when code changes.
Key Takeaways
Create a Dockerfile to containerize your Spring Boot app with a Java base image and jar copy.
Define your app service in docker-compose.yml with build context and port mapping.
Run your app using docker-compose up to start the container easily.
Ensure ports are correctly mapped and the jar is built before running containers.
Use docker-compose up --build to rebuild images after code changes.