Docker-Compose: Ensuring MySQL Connection Readiness before Service Startup
In a Docker-compose environment, it is crucial to ensure that dependent services, such as databases, are ready for connections before other services relying on them start. This article provides a solution for checking MySQL connection readiness using the healthcheck option in Docker-compose version 2.
Healthcheck Configuration
To set up a healthcheck for the MySQL container, define it within the container's configuration. Below is an example healthcheck:
healthcheck: test: ["CMD", "mysqladmin", "ping", "-h", "localhost"] timeout: 20s retries: 10
This healthcheck uses the mysqladmin ping command to verify if MySQL is running and accepting connections. If the command returns successfully within the specified timeout and retry limits, the container is considered healthy.
Depending on Healthy Service
Once the healthcheck is defined, the dependent service (in this case, an "app" container) can specify a dependency on the MySQL container using the depends_on option:
app: depends_on: db: condition: service_healthy
This configuration ensures that the "app" container only starts if the "db" container (MySQL) is healthy according to the defined healthcheck.
Example Docker-compose File
Putting it all together, here is an example Docker-compose file that uses this setup:
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
With this configuration, the "api" container will not start until the "db" container (MySQL) is healthy and accepting connections, ensuring that the database is ready before the app starts.
The above is the detailed content of How to Ensure MySQL Connection Readiness Before Starting Dependent Services in Docker Compose?. For more information, please follow other related articles on the PHP Chinese website!