Protecting Sensitive Information in Docker Compose

Tags: docker docker-compose sensitive information

Hide Yo Passwords!

If you have multiple containers in a swarm service, this won't be the path for you. If you do have a docker swarm service, check out docker secrets.

I however, don't have a swarm, and I don't see any benefit in converting my setup into a swarm of size one, as the docker secret docs offer as a suggestion. So instead, I'll be using good ol' environment variables. The problem however, is that I want to share as much of my code publicly as possible but without exposing any sensitive information. To this end, I'll be using the handy env_file option in my docker-compose file.

You can specify the file location like so:

version: '3'

  # PostGIS database
    env_file: /opt/db_secrets.env
    image: my_postgis

  # Redis
    image: redis:3.2.11
    hostname: redis

  # RabbitMQ
    hostname: rabbit
    image: rabbitmq:3.7.2
    env_file: /opt/rabbit_secrets.env

  # Django web server
    build: .
    env_file: /opt/django_secrets.env
    command: python runserver
      - .:/code
      - "8000:8000"
      - db

I've opted to store my environment variable files in the /opt directory, far from my source control directory so I don't accidently end up pushing anything I don't intend to make public.

Make sure to define the environment variables within those files using the following notation, with one credential per line:


Now, the only thing left to do is modify the file permissions for the sake of the docker container:

sudo chown root:docker rabbit_secrets.env
sudo chmod 740 /opt/rabbit_secrets.env

And now you're ready to roll.