Careeroza
docker-compose with MySQL
The Whole Stack Locally
Example
docker-compose.yml
services:
mysql:
image: mysql:8.4
environment:
MYSQL_DATABASE: shopease
MYSQL_USER: shopease
MYSQL_PASSWORD: ${DB_PASSWORD}
MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD}
volumes:
- mysql-data:/var/lib/mysql
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
interval: 5s
retries: 10
redis:
image: redis:7
app:
build: .
ports:
- "8080:8080"
environment:
SPRING_PROFILES_ACTIVE: prod
SPRING_DATASOURCE_URL: jdbc:mysql://mysql:3306/shopease
SPRING_DATASOURCE_USERNAME: shopease
SPRING_DATASOURCE_PASSWORD: ${DB_PASSWORD}
SPRING_DATA_REDIS_HOST: redis
depends_on:
mysql:
condition: service_healthy
redis:
condition: service_started
volumes:
mysql-data:Example
Secrets come from a .env file next to it (add it to .gitignore):
echo "DB_PASSWORD=change-me" > .env
echo "DB_ROOT_PASSWORD=change-me-too" >> .env
docker compose up -d --build
docker compose psExample output
NAME IMAGE STATUS PORTS shopease-mysql-1 mysql:8.4 Up 40 seconds (healthy) 3306/tcp, 33060/tcp shopease-redis-1 redis:7 Up 40 seconds 6379/tcp shopease-app-1 shopease-app Up 12 seconds 0.0.0.0:8080->8080/tcp
Spring Boot Docker Compose Support
For development, add spring-boot-docker-compose. When you run the app from the IDE, Spring Boot starts the services in compose.yaml and wires the datasource and Redis connection automatically.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-docker-compose</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>