If you’ve worked with Docker Compose in the past, you may have used a number of tricks to make sure that the containers were stable and running before moving on to further steps. For example, you might periodically ping the service. If the attempt fails, you simply sleep and retry until you get the expected results.
A short time ago, the Docker team offered an easier approach to solving this problem. Just wait for it. More to the point, they added the --wait
command. This ensures that docker compose up
waits for your services to be healthy before returning control to the caller. This can be helpful, especially if you’re using Compose to automate other processes.
The new switch works by waiting for the configured health checks to succeed (or fail) before the command returns. This requires configuring the healthcheck
YAML attribute. For example:
1healthcheck:
2 test: ["CMD", "curl", "--fail", "http://localhost/health"]"
3 interval: 30s
4 retries: 4
5 start_period: 10s
6 timeout: 20s
A health check has 5 properties:
- test
- The command to execute to determine if the container is healthy. A healthy container returns a status code 0. Strings are executed using the shell, while arrays must start with “NONE” (disabled health check), “CMD” (direct execution), or “CMD-SHELL” (invoke using the shell).
- interval
- How much time to wait before each check (including the first).
- retries
- The maximum number of failures before declaring the container unhealthy
- start_period
- How long to wait for the container to start before beginning a health check. During this time, non-zero health check results will not be considered.
- timeout
- The number of seconds to wait for the test to complete for automatically declaring a failure.
Taken together, these give you a way to configure and control the process. You’re providing a command, so you can apply whatever logic is necessary to ensure each container is healthy and available.