CodexBloom - Programming Q&A Platform

Docker Compose Service Dependencies Not Starting in Correct Order

👀 Views: 870 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-03
docker docker-compose devops yaml

Could someone explain After trying multiple solutions online, I still can't figure this out..... I'm working with an scenario with my Docker Compose setup where services are not starting in the expected order, leading to connection errors. I have a multi-container application consisting of a web service, a database, and a caching layer. The web service needs to connect to the database before it can start accepting requests, but it seems like the web service is trying to connect to the database before it's fully ready. My `docker-compose.yml` file looks like this: ```yaml version: '3.8' services: web: image: my-web-app:latest depends_on: - db environment: DATABASE_URL: "postgres://user:password@db:5432/mydb" db: image: postgres:13 environment: POSTGRES_USER: user POSTGRES_PASSWORD: password POSTGRES_DB: mydb cache: image: redis:6 ``` Despite using `depends_on`, the web service is still trying to connect to the database too early. I checked the logs for the web service and I see: ``` behavior: connect ECONNREFUSED 172.18.0.3:5432 ``` I even tried adding a custom wait script in the entrypoint of the web service that checks for the database availability: ```bash #!/bin/sh set -e until psql -h db -U user -d mydb -c 'SELECT 1'; do >&2 echo "Database is unavailable - sleeping" sleep 5 done >&2 echo "Database is up - executing command" exec "$@" ``` However, I still run into connection issues. I've also verified that the database is indeed running and accepting connections after a while, so it seems like a timing scenario. What else can I do to ensure the web service waits until the database is fully ready before it attempts to connect? My development environment is macOS. I'd really appreciate any guidance on this. I've been using Yaml for about a year now. What are your experiences with this? The stack includes Yaml and several other technologies. For context: I'm using Yaml on Ubuntu 20.04. Hoping someone can shed some light on this.