Search code examples
mysqldockerdocker-composemariadbdocker-swarm

MYSQL_ROOT_PASSWORD environment variable is not set for mariadb container if I using .env file in swarm


When I try to set up a cluster with docker swarm I receive this error:

$ docker logs 6ea0f7290cb0  
2020-11-30 10:46:08+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 1:10.5.8+maria~focal started.
2020-11-30 10:46:08+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
2020-11-30 10:46:08+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 1:10.5.8+maria~focal started.
2020-11-30 10:46:08+00:00 [ERROR] [Entrypoint]: Database is uninitialized and password option is not specified
        You need to specify one of MYSQL_ROOT_PASSWORD, MYSQL_ALLOW_EMPTY_PASSWORD and MYSQL_RANDOM_ROOT_PASSWORD

What is weird because if I use the docker-compose tool, everything works well.

To replicate this problem follow the steps below.

Create a .env file:

DB_NAME=nest
DB_USERNAME=nest
DB_PASSWORD=nest
DB_ROOT_PASSWORD=nest

Create a docker-compose.yml file:

version: '3.8'

services:

  db:
    image: mariadb
    environment:
      MYSQL_ROOT_PASSWORD: "${DB_ROOT_PASSWORD}"

If I use the command docker-compose up -d, I can check that everything works well with the docker-compose ps command:

$ docker-compose ps
    Name                  Command             State    Ports  
--------------------------------------------------------------
db-debug_db_1   docker-entrypoint.sh mysqld   Up      3306/tcp

If I use the command docker stack deploy -c docker-compose.yml db, I can check that the database is not started with the command docker service ls:

$ docker service ls
ID                  NAME                MODE                REPLICAS            IMAGE               PORTS
ux1p4k6vwiyh        db_db               replicated          0/1                 mariadb:latest

Solution

  • docker-compose and docker stack deploy have a number of differences in how they parse the compose.yml file. One of them being that the latter does not automatically process a .env files. (reference) As such you need to explicitly reference it:

    services:
      db:
        image: mariadb
        env_file: .env