dockerdocker-composemariadb

How to properly configure MariaDB healthcheck in Docker Compose without access denied warnings?


I'm using MariaDB image in my docker-compose.yml and I wanted to add a health check as recommended.

The official MariaDB image provides a healthcheck.sh script that I tried to use. However, after starting the container, I encountered the following warning in the logs:

2025-02-14  7:43:29 3 [Warning] Access denied for user 'root'@'::1' (using password: NO)

From my research, I learned that healthcheck.sh creates its own user, and it doesn't commit itself to the environment variables that I am passing to the container that are related to MariaDB. To work around this, I created a script set_healthcheck_user.sh to explicitly set the credentials for the health check in /etc/mysql/healthcheck.cnf:

#!/bin/bash

cat <<EOF > /etc/mysql/healthcheck.cnf
[client]
user=${MARIADB_USER}
password=${MARIADB_PASSWORD}
host=localhost
EOF

This approached worked, and the health check succeeded without the warning. However, I'm wondering if there’s a better or more standard way to configure the MariaDB health check in Docker Compose without adding healthcheck.cnf manually.

Here is part of my docker-compose.yml file which is related to the database service

db:
  container_name: mariadb
  image: ${CI_DEPENDENCY_PROXY_DIRECT_GROUP_IMAGE_PREFIX}/mariadb:10.6.11
  command: /bin/bash -c "chmod +x /docker-entrypoint-initdb.d/set_healthcheck_user.sh && /docker-entrypoint-initdb.d/set_healthcheck_user.sh && docker-entrypoint.sh mysqld"
  restart: always
  healthcheck:
    test: [ "CMD", "healthcheck.sh", "--defaults-file=/etc/mysql/healthcheck.cnf", "--connect", "--innodb_initialized" ]
    start_period: 10s
    interval: 10s
    timeout: 5s
    retries: 3
  ports:
    - "3307:3306"
  volumes:
    - ./docker_services/database/set_healthcheck_user.sh:/docker-entrypoint-initdb.d/set_healthcheck_user.sh:rw
    - mariadb_data:/var/lib/mysql

Solution

  • A DATADIR (/var/lib/mysql) containing .my-healthcheck.cnf configuration file should exist in fairly modern containers so no explicit configuration should be necessary.

    A healthcheck user is created so it will be independent of the root user.

    If you started on an older datadir you can use MARIADB_AUTO_UPGRADE=1 as an environment variable which will recreate the users and configuration file if the configuration file is missing.