• June 22, 2022

MySql in docker - common issues

The problem:

Before the database container is loaded, the application wants to execute some query to the DB. Typically, this is related to migrations when creating a completely new project instance. Since the database does not respond, the application container is killed.

The solution?

A simple solution is to add HealthCheck to the DB ping and add a dependency (depends_on) in the application container if the database container is healthy.

An example

HealthCheck

Is added to a db service

healthcheck:
    test: [ "CMD", "mysqladmin" ,"ping", "-h", "localhost" ]
    timeout: 5s
    interval: 5s
    retries: 10

Dependency

It is added to the application service.

depends_on:
    db:
        condition: service_healthy

The result

The resulting "trimmed" docker-compose:

version: "3.8"

services:
    db:
        image: "mysql:8"
    =>  healthcheck:
            test: [ "CMD", "mysqladmin" ,"ping", "-h", "localhost" ]
            timeout: 5s
            interval: 5s
            retries: 10
        command: [ "mysqld", "--character-set-server=utf8", "--collation-server=utf8_general_ci" ]
    app:
        build: .
        command: [ "sh", "-c", "scripts/run_server.sh" ]
        env_file:
            - .env
        ports:
            - "8000:8000"
    =>  depends_on:
            db:
                condition: service_healthy

Zajímá Vás víc?

Neváhejte nás kontaktovat.