How to use Docker secrets in a Docker Compose file?
Published on Aug. 22, 2023, 12:19 p.m.
To use Docker secrets in a Docker Compose file, you can follow these steps:
- Create a secret using the docker secret create command:
docker secret create mysecret /path/to/secret/file
This command will create a Docker secret named “mysecret” from the file located at “/path/to/secret/file”.
2. Reference the secret in your Docker Compose file:
version: "3.9"
services:
myapp:
image: myapp:latest
secrets:
- mysecret
This code specifies that the “myapp” service requires the “mysecret” secret.
3. Run the Docker Compose file:
docker-compose up
This command will start the services defined in the Docker Compose file and provide the secret “mysecret” to the “myapp” service.
And that’s it! Docker Compose will automatically make the secret available to the specified services at the path “/run/secrets/mysecret”. Note that Docker Compose does not support reading secrets from environment variables directly. Instead, mount the secret to a file and read the file from the container instead.
Also, keep in mind that secrets can only be used with swarm services, not with standalone containers.