1. Define Secrets in Docker Compose:
In your docker-compose.yml
file, you can define secrets under the secrets
key. Here’s an example:
version: '3.7'
services:
db:
image: mysql
environment:
MYSQL_ROOT_PASSWORD_FILE: /run/secrets/db_root_password
secrets:
- db_root_password
secrets:
db_root_password:
file: ./db_root_password.txt
In this example:
- We define a service called
db
that uses the MySQL image. - We set the
MYSQL_ROOT_PASSWORD_FILE
environment variable to/run/secrets/db_root_password
. This tells MySQL to read the mysql root password from this file. - We define a secret named
db_root_password
which will be populated from the content of thedb_root_password.txt
file.
2. Create a Secrets File:
Create a file named db_root_password.txt
in the same directory as your docker-compose
file. Add the root password to this file. For security reasons, it’s recommended to set proper file permissions to restrict access to this file.
3. Deploy the Stack:
To deploy your docker-compose stack with secrets, run:
docker-compose up -d
This command will start the services defined in your docker-compose.yml
file, with the secrets provided securely.
4. Accessing Secrets Inside Containers:
In the docker-compose db
service configuration, we set the MYSQL_ROOT_PASSWORD_FILE
environment variable to /run/secrets/db_root_password
. Inside the db
container, MySQL will read the root password from the /run/secrets/db_root_password
file.
5. Updating Secrets:
If you need to update a secret, you can simply update the content of the corresponding file (db_root_password.txt
in this example) and then redeploy your Docker Compose stack using docker-compose up -d
.
6. Managing Multiple Secrets:
You can define multiple secrets in the secrets
section of your docker-compose file to manage multiple sensitive pieces of information for your services.
This way you can effectively manage secrets for your docker-compose services, ensuring that sensitive information is kept secure and only accessible to the services that need it.