Securing Docker Compose Secrets
Published: 2022-09-02When using Docker Compose on servers, it is important to be reasonably careful with secrets such as passwords and keys. For professional use, there exist many services to store secrets such as HashiCorp Vault and Docker Secrets. However, for personal use, these services introduce a risky dependency. The risks are that you get locked out, that they stop supporting the software, or that you have to pay too much money per month. Also, most of the professional services are too complicated for our purposes.
Setting enviroment variables
For personal use, we need to make it reasonably difficult for intruders to access our secrets. So, the following docker-compose.yml
is not safe:
version: '3'
services:
database:
image: 'mysql/8-debian'
environment:
MYSQL_ROOT_PASSWORD: '52BrE29M4e8So4'
With this file, anyone obtaining access to the file will know the secret which in this case is 52BrE29M4e8So4
. A much safer method is to put the secrets in .env
files. First, make sure to not store any .env
file inside Git. To ensure that, add the following to .gitignore
:
**/*.env
This will not track any file ending with .env
. Then, to use .env
files, create the following docker-compose.yml
file:
version: '3'
services:
database:
image: 'mysql/8-debian'
env_file:
- 'MYSQL_ROOT_PASSWORD.env'
with the following MYSQL_ROOT_PASSWORD.env
file:
MYSQL_ROOT_PASSWORD=52BrE29M4e8So4
To make this MYSQL_ROOT_PASSWORD.env
file available on different computers and servers, create the files manually and copy the secrets from your password manager.
With this, only attackers with access to your local system or to the server can see the secrets.
What not to do
One thing to avoid is to pass secret via the command line. For example, don't use:
$ docker run --env="MYSQL_ROOT_PASSWORD=52BrE29M4e8So4" mysql/8-debian
since this will make the password show up in the list of running services, in logs, and in your shell's history.