How to Serve a Spring Boot Project with Docker
Introduction
This blog post will guide you through the process of containerizing a Spring Boot application using Docker. We’ll cover setting up the necessary environment with MySQL and Redis, and then running your application within a Docker container.
Prerequisites
- Docker installed on your system.
- A Spring Boot project ready to be containerized.
- Basic understanding of Docker concepts.
Setting up the Environment with Docker Compose
Docker Compose is a tool for defining and running multi-container Docker applications. We’ll use it to orchestrate our Spring Boot application, MySQL, and Redis containers.
Create a docker-compose.yml
file in the root of your Spring Boot project with the following content:
1 | version: "3.9" |
Explanation:
- version: Specifies the Docker Compose file version.
- services: Defines the different services (containers) that make up your application.
- app: This service builds your Spring Boot application using the
Dockerfile
in the current directory (.
). It exposes port 8080 and depends onmysql
andredis
services. Environment variables are set for database and Redis connection details. - mysql: This service uses the official MySQL 8.0 image. It exposes port 3306 and sets environment variables for the root password, database name, username, and password.
- redis: This service uses the official Redis image and exposes port 6379.
Important: Replace your_database
, your_username
, your_password
, and your_root_password
with your actual database credentials.
Creating the Dockerfile
Create a Dockerfile
in the root of your Spring Boot project with the following content:
1 | FROM openjdk:17-jdk-slim |
Explanation:
- FROM: Specifies the base image to use (OpenJDK 17).
- VOLUME: Creates a volume for temporary files.
- COPY: Copies the Spring Boot JAR file from the
target
directory to the/app.jar
file in the container. - ENTRYPOINT: Sets the command to run when the container starts (java -jar /app.jar).
Building and Running the Application
Open a terminal in the root of your Spring Boot project and run the following command:
1 | docker-compose up --build |
This command will:
- Build the Spring Boot application image.
- Start the MySQL and Redis containers.
- Start the Spring Boot application container.
Your application should now be running at http://localhost:8080
.
Conclusion
This blog post demonstrated how to containerize a Spring Boot application with Docker, including setting up the environment with MySQL and Redis using Docker Compose. This approach provides a consistent and reproducible environment for your application, making it easier to deploy and manage.