In the realm of Docker containers, ensuring that applications start only when their required dependencies are ready is crucial. This is especially important for databases like MySQL, which need to be initialized and prepared before accepting connections.
In Docker Compose, the depends_on and healthcheck options provide a means to control the dependency relationship between containers. The depends_on option specifies that a container should wait until the specified dependency is healthy before starting. The healthcheck option, on the other hand, defines a rudimentary test to determine the healthiness of a container.
When attempting to validate MySQL readiness, various methods have been explored:
A solution that ensures MySQL is ready before starting other containers is as follows:
version: "2.1" services: api: build: . container_name: api ports: - "8080:8080" depends_on: db: condition: service_healthy db: container_name: db image: mysql ports: - "3306" environment: MYSQL_ALLOW_EMPTY_PASSWORD: "yes" MYSQL_USER: "user" MYSQL_PASSWORD: "password" MYSQL_DATABASE: "database" healthcheck: test: ["CMD", "mysqladmin" ,"ping", "-h", "localhost"] timeout: 20s retries: 10
In this configuration, the api container will not start until the db container is healthy, which is determined by the "ping" test in the healthcheck configuration. The "ping" test verifies that the MySQL server is reachable and can accept connections, ensuring that the api container can safely start its operations.
The above is the detailed content of How to Ensure MySQL Readiness in Docker Compose Before Starting Dependent Services?. For more information, please follow other related articles on the PHP Chinese website!