Home >Database >Mysql Tutorial >How Can I Ensure My Docker Compose Application's Database is Ready Before Startup?

How Can I Ensure My Docker Compose Application's Database is Ready Before Startup?

DDD
DDDOriginal
2024-12-11 15:23:11419browse

How Can I Ensure My Docker Compose Application's Database is Ready Before Startup?

Ensuring Database Readiness for Docker Compose Applications

To prevent premature execution of database migrations or application startup, it is crucial to ensure that the database container is fully operational before the app container initiates its processes. Using Docker Compose's healthcheck and depends_on options, a mechanism can be established to verify database connectivity and delay app startup until the database is ready.

In the provided example, the healthcheck for the database container (db) utilizes the mysqladmin command to ping the localhost and check if the database is accepting connections. This test ensures that the database is not only up but is also accessible.

Here's a modified version of the provided Docker Compose file:

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 remain in a suspended state until the db container successfully passes the healthcheck, indicating that the database is fully operational and ready for connections. This ensures that the app will not attempt to perform migrations or start processing until the database is accessible, preventing potential issues or data integrity errors.

The above is the detailed content of How Can I Ensure My Docker Compose Application's Database is Ready Before Startup?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn