jav spring boot mastery

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:

  • FROM defines the base image.
  • COPY moves the JAR file into the container.
  • ENTRYPOINT tells 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_on ensures MySQL starts before the app.
  • Sets environment variables for Spring configuration.

🚀 3. Deploy to Cloud (e.g., AWS EC2)

Steps:

  1. SSH into your EC2 instance.
  2. Install Docker and Docker Compose.
  3. Copy your project and docker-compose.yml to the server.
  4. Run: docker-compose up -d

➡️ Next Up: Part 14 – Spring Boot with CI/CD using GitHub Actions or Jenkins

Similar Posts