Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docker compose healthcheck use environment variables

Here is my docker-compose.yml:

version: "3"

services:
  mongodb:
    image: mongo:4.1
    volumes:
      - ./mongodb_data:/data/db
    container_name: mongodb
    ports:
      - 27017:27017
  mysql:
    image: mysql:5.7
    #volumes:
    #- ./mysql_data:/var/lib/mysql
    container_name: mysqldb
    ports:
    - 3306:3306
    - 33060:33060
    expose:
    - 3306
    - 33060
    environment:
    - MYSQL_ROOT_PASSWORD=password
    - MYSQL_DATABASE=somedb
    - MYSQL_USER=rstudio
    - MYSQL_PASSWORD=password
    healthcheck:
      test: ["CMD", "mysql", "--user=$MYSQL_USER", "--password=$MYSQL_PASSWORD", "-e", "'SHOW DATABASES;'"]
      timeout: 5s
      retries: 5

How can I use environment variables MYSQL_USER and MYSQL_PASSWORD? In current setup I got following warning when running docker compose:

WARNING: The MYSQL_USER variable is not set. Defaulting to a blank string.
WARNING: The MYSQL_PASSWORD variable is not set. Defaulting to a blank string.
like image 276
Taz Avatar asked Mar 04 '19 17:03

Taz


Video Answer


2 Answers

You need to use double-dollar sign ($$) in order to tell docker-compose not to parse these environment variables. Also change the way of defining a test as I tried to make it work but I couldn't without changing it. The following should work as expected:

test: mysql --user=$$MYSQL_USER --password=$$MYSQL_PASSWORD -e 'SHOW DATABASES;'

docker ps result: Up 35 seconds (healthy)

like image 73
Mostafa Hussein Avatar answered Sep 20 '22 18:09

Mostafa Hussein


Your YAML looks OK, how are you invoking your env variables? Make sure you're referencing the correct object. Generally from your application you'd invoke your variables using something like

process.env.MYSQL_USER

You also don't need the dashes, my preference (for readibility) would be this syntax:

mysql:
  environment:
    MYSQL_ROOT_PASSWORD: password
    MYSQL_DATABASE: somedb
    MYSQL_USER: rstudio
    MYSQL_PASSWORD: password

If you're trying to reference your env variable in the yaml config directly (i.e. in your tests command) you should use ARGS instead as your env variables probably won't be compiled yet.

EDIT - if you want to reference an object within the yaml, you could use self e.g.:

test: ["CMD", "mysql", "--user=${self:services.mysql.environment.MYSQL_USER}", "--password=${self:services.mysql.environment.MYSQL_PASSWORD}", "-e", "'SHOW DATABASES;'"]
like image 42
contool Avatar answered Sep 18 '22 18:09

contool