These days, many developers are using
docker-compose to build system on our local machines. If each container does not depend on each other, the system is simple. However, we usually have dependent and dependency containers within our docker-compose networks. I'm sharing the most basic cases of dependent-dependency pattern and how to boot containers in a order that we expect.
Docker has healthcheck functionality. The rules can be written in our Dockerfile or docker-compose. In docker-compose, it is written like following. The
server container relies on
db should have
healthcheck section and the condition.
server should have
db in the
depends_on and the condition underneath to make sure that it boots after the
db container gets health status.
services: server: image: your_server_image depends_on: db: condition: service_healthy db: image: your_db_image healthcheck: test: ... # Command to check health. interval: 5s # Interval between health checks. timeout: 5s # Timeout for each health checking. retries: 20 # Hou many times retries. start_period: 10s # Estimated time to boot.
Maintain server and MySQL containers in the same docker-compose runtimes is a very common pattern. The server must be booted after the MySQL container gets ready if you want to do something like table migrations when the server container booted. Pinging with
mysqladmin to MySQL server in the db container, we can check if MySQL is ready. The MySQL server runs on localhost in the contianer, the host
-h parameter must be
localhost. The password is the one you set in the
environment section with the
db: image: mysql:8.0.26 ports: - 3316:3306 environment: MYSQL_DATABASE: yourdb MYSQL_ROOT_PASSWORD: pass healthcheck: test: ["CMD", "mysqladmin" ,"ping", "-h", "localhost", "-uroot", "-ppass"] interval: 5s timeout: 5s retries: 20
If we have more than 1 server, the servers may depends on others. e.g. In an image detection service system, one main server for user access and another server for image detection by machine learning. For the case, self-pinging should be the simplest solution. For the server runs on
8080 port in the container,
curl command to ping should be like the below.
image_detection: image: your_image ports: - 8082:8080 healthcheck: test: "curl -f localhost:8080" interval: 5s timeout: 5s retries: 20