Write down Docker Compose file for Spring Boot, Hibernate and MySQL application
Here's an example Docker Compose file for a Spring Boot app that uses Hibernate for JPA and MySQL as the database. This sample assumes you have a Spring Boot app with a Dockerfile
for packaging and an application.properties
file to set up the database connection.
- Dockerfile (in the root of your Spring Boot project):
# Use AdoptOpenJDK 11 base image
FROM adoptopenjdk:11-jre-hotspot
# Set the working directory
WORKDIR /app
# Copy the JAR file into the container
COPY target/your-spring-boot-app.jar /app/app.jar
# Expose the port your app will run on
EXPOSE 8080
# Command to run the application
CMD ["java", "-jar", "app.jar"]
- application.properties (in the
src/main/resources
directory of your Spring Boot project):
# Spring Datasource configuration
spring.datasource.url=jdbc:mysql://mysql-container:3306/your_database_name
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# Hibernate configuration
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
# Other Spring Boot configurations
- docker-compose.yml (in the root of your project):
version: '3'
services:
# MySQL Service
mysql-container:
image: mysql:8.0
environment:
MYSQL_ROOT_PASSWORD: root_password
MYSQL_DATABASE: your_database_name
MYSQL_USER: your_username
MYSQL_PASSWORD: your_password
ports:
- "3306:3306"
# Spring Boot Service
spring-boot-app:
build:
context: .
dockerfile: Dockerfile
ports:
- "8080:8080"
depends_on:
- mysql-container
environment:
SPRING_DATASOURCE_URL: jdbc:mysql://mysql-container:3306/your_database_name
SPRING_DATASOURCE_USERNAME: your_username
SPRING_DATASOURCE_PASSWORD: your_password
volumes:
- ./src/main/resources:/app/src/main/resources # Map local resources directory to container
Explanation:
The
mysql-container
service uses the official MySQL image, sets up needed environment variables to create a database and user, and opens port 3306.The
spring-boot-app
service builds the Spring Boot app with the given Dockerfile. It relies on themysql-container
service and sets environment variables to connect the Spring Boot app to the MySQL database.The volumes section in the
spring-boot-app
service maps the localsrc/main/resources
folder to the container. This helps quickly reload changes to theapplication.properties
file during development.
To use this Docker Compose setup, check that you have a valid Dockerfile
for your Spring Boot app, and change the application.properties
file with your MySQL connection info. Next, run these commands:
docker-compose up
This will create and start both the MySQL and Spring Boot containers. Access your Spring Boot application at http://localhost:8080
. To stop and remove the containers, use:
docker-compose down