Spring Boot with Docker & Deployment [Java Spring Boot Mastery Series – Part 13]
🚀 Why Use Docker?
Docker allows you to package your application with all its dependencies into a single container, ensuring consistency across environments.
🛠️ 1. Dockerize a Spring Boot App
Step 1: Add Dockerfile
FROM openjdk:17-jdk-slim
VOLUME /tmp
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","/app.jar"]
Step 2: Build the Docker Image
docker build -t springboot-app .
Step 3: Run the Container
docker run -p 8080:8080 springboot-app
Explanation:
FROMdefines the base image.COPYmoves the JAR file into the container.ENTRYPOINTtells Docker how to start the app.
🧪 2. Use Docker Compose (For MySQL Integration)
docker-compose.yml
version: '3.8'
services:
mysql:
image: mysql:8
container_name: mysqldb
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: springdb
ports:
- '3306:3306'
app:
build: .
ports:
- '8080:8080'
depends_on:
- mysql
environment:
SPRING_DATASOURCE_URL: jdbc:mysql://mysqldb:3306/springdb
SPRING_DATASOURCE_USERNAME: root
SPRING_DATASOURCE_PASSWORD: root
Run the Compose Setup
docker-compose up --build
Explanation:
- Starts MySQL and Spring Boot app together.
depends_onensures MySQL starts before the app.- Sets environment variables for Spring configuration.
🚀 3. Deploy to Cloud (e.g., AWS EC2)
Steps:
- SSH into your EC2 instance.
- Install Docker and Docker Compose.
- Copy your project and
docker-compose.ymlto the server. - Run:
docker-compose up -d
➡️ Next Up: Part 14 – Spring Boot with CI/CD using GitHub Actions or Jenkins
