?? Building and Deploying a Spring Boot Application with Docker
Pankaj Chaudhari
AWS Certified | Software Engineer | Expertise in Java, Spring Boot, Hibernate, Docker
I’m excited to share a recent project where I developed a Spring Boot application and successfully deployed it using Docker. Here’s a step-by-step breakdown of the process, from creating the JAR file to deploying it in a Docker container.
?? Developing the Spring Boot Application
I developed a Spring Boot application designed to manage banking operations, incorporating features like Swagger for API documentation and MySQL for database management. The goal was to ensure the application was not only functional but also easily deployable and maintainable in various environments.
The project code is available in my GitHub repository
https://github.com/pankajpc15/banking-service-api
Note: If you want to try this on your own, clone the repository from banking-service-api then navigate to the project directory and run follwing command.
?? Docker Deployment: The Key to Flexibility:
mvn clean package
This command generated a JAR file in the target directory, which included all the compiled code and dependencies needed to run the application.
2. Building the Docker Image:
With the JAR file ready, I created a Docker image for the Spring Boot application. I wrote a Dockerfile that defined how the Docker image should be built. Here’s a simplified version of the Dockerfile:
领英推荐
# Use the official OpenJDK base image
FROM openjdk:20-jdk-slim
# Set the working directory
WORKDIR /app
# Copy the JAR file into the container
COPY banking-service-0.0.1-SNAPSHOT.jar app.jar
# Expose the port the app runs on
EXPOSE 8090
# Run the JAR file
ENTRYPOINT ["java", "-jar", "app.jar"]
I then built the Docker image using the following command:
docker build -t banking-service:v1 .
3. Creating and Running the Docker Container:
version: '3.8'
services:
mysql:
image: mysql:8.0
container_name: mysql-container
environment:
MYSQL_ROOT_PASSWORD: 1234
MYSQL_DATABASE: banking_db
volumes:
- mysql-data:/var/lib/mysql
networks:
- banking-network
ports:
- "3306:3306"
springboot:
image: banking-service:v1
container_name: banking-service-container
environment:
SPRING_PROFILES_ACTIVE: docker
ports:
- "8090:8090"
networks:
- banking-network
depends_on:
- mysql
volumes:
mysql-data:
networks:
banking-network:
I started the containers with the following command:
docker-compose up -d
This command launched the application and MySQL services, making the Spring Boot application accessible at
https://localhost:8090/swagger-ui.html
final output: