How to ensure a delay at the start of a service in Docker Compose so that it does not accept incoming requests until it is fully ready?
sobes.tech AI
Answer from AI
To prevent a service in Docker Compose from accepting requests until it is fully ready, the common approach is to use the "healthcheck" mechanism and start delay with wait scripts.
Main approaches:
-
Healthcheck in docker-compose.yml — define a command that checks the service's readiness (for example, an API request or port check). Other services can depend on the health status.
-
Wait script (wait-for-it, dockerize, or custom) — add a script in the service's entrypoint that waits for the availability of a required resource (such as a database) before starting the main process.
Example healthcheck in docker-compose.yml:
services:
app:
image: myapp
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
interval: 10s
timeout: 5s
retries: 5
Or use a wait script in Dockerfile:
ENTRYPOINT ["./wait-for-it.sh", "db:5432", "--", "./start-app.sh"]
Thus, the service will not start accepting requests until it is ready.