Before you go, check out these stories!

0
Hackernoon logoHow To Use Environment Variables In Docker Compose File by@ifomin

How To Use Environment Variables In Docker Compose File

Author profile picture

@ifominIgor Fomin

Full stack web developer, tech lead, project manager

If I want to use different credentials on different servers, environment variables work great with docker compose.

As an example I will use docker-compose.yml file from Docker + Redis + Redis Commander article.

Source files can be found here: https://github.com/ikknd/docker-study in folder recipe-07

version: "3.7"

services:

  redis:
    image: redis:latest
    ports:
      - 6379:6379
    command: ["redis-server", "--appendonly", "yes"]
    volumes:
      - redis-data:/data

  redis-commander:
    image: rediscommander/redis-commander:latest
    environment:
      - REDIS_HOSTS=local:redis:6379
      - HTTP_USER=${REDIS_USER:-admin}
      - HTTP_PASSWORD=${REDIS_PASSWORD:-qwerty}
    ports:
      - 8081:8081
    depends_on:
      - redis
    
volumes:
  redis-data:

Notes:

  • HTTP_USER=${REDIS_USER:-admin} - here I use ${REDIS_USER:-admin} syntax, which means - use REDIS_USER variable from .env file, in case it is missing, use "admin" instead.
  • .env file gets picked up automatically when running "docker-compose up -d", there is no need to specify it somehow

If I now try this docker-compose.yml file without .env file, credentials to redis-commander will be admin/qwerty.

If I create .env file next to my yml file and put the following inside, credentials to redis-commander will be test/1234:

REDIS_USER=test
REDIS_PASSWORD=1234

Tags

The Noonification banner

Subscribe to get your daily round-up of top tech stories!