dev3 ·
My app container starts before MySQL is ready and crashes with "Connection refused". I used depends_on, but it did not help. How do I fix it properly?
0
DEV3 Developer Forum
Every post is reviewed first. Usually reviewed within 24 hours.
My app container starts before MySQL is ready and crashes with "Connection refused". I used depends_on, but it did not help. How do I fix it properly?
depends_on alone only controls start order, not readiness. Add a healthcheck and use the service_healthy condition (Compose v2 / Compose Specification).
services:
app:
build: .
ports:
- "8080:8080"
environment:
DB_HOST: db
DB_DATABASE: app
DB_USERNAME: app
DB_PASSWORD: ${DB_PASSWORD}
depends_on:
db:
condition: service_healthy
restart: unless-stopped
db:
image: mysql:8.4
environment:
MYSQL_DATABASE: app
MYSQL_USER: app
MYSQL_PASSWORD: ${DB_PASSWORD}
MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD}
volumes:
- dbdata:/var/lib/mysql
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-p${DB_ROOT_PASSWORD}"]
interval: 5s
timeout: 3s
retries: 20
volumes:
dbdata:
Key points
db), not localhost.localhost inside the app container is the app itself. This is the usual cause of "Connection refused"..env file next to the compose file (never commit it).dbdata keeps data across docker compose down; down -v deletes it.3306:3306) on a public server unless required; the app reaches it on the internal network.Also make the app retry connections; healthchecks do not cover a DB restart while running. Commands: docker compose up -d, docker compose logs -f app, docker compose ps.
You can scaffold files with the Dockerfile and Compose generator.