How to use Docker Secrets In Docker
After creating docker secrets, using them can be done in multiple ways:
- It could be used with the help of Docker compose in the docker-compose.yml file by adding a key-value pair of “secrets”.
- It can also be used in the Dockerfile with an environment variable.
- It is also used in sidecar containers with the help of a different mounted volume.
To discuss the ways in detail
1. To use docker secret with docker-compose.yml we need to specify the name of our secrets within the services block of the yaml file. And further need to specify the path/location/value of the secrets in a separate block in the yaml. A sample code for the above could be this:
version: '3.4'
services:
demo_application:
image: demo_application:latest
volumes:
- /var/lib/demo_application
secrets:
- demo_secret
secrets:
demo_secret:
file: /Desktop/demo_secret.txt
This method ensures that the secrets are only accessible to the services to which access has been explicitly authorized and that secrets live only in memory while that service is active, in contrast to the other methods.
2. To use docker secret with Dockerfile, we need to use the ENV instruction as well as the docker get secret command for retrieving that particular secret. A sample for this could be:
ENV DEMO_SECRET $(docker secret get demo_secret)
Using this method, the secret will be encrypted and stored in the image when we create our Docker image. The secret will be decrypted and made available to the container as an environment variable when the container is started by the Docker daemon.
3. To use docker secret with sidecar containers, we again need to modify the docker-compose.yml file. Here we need to mount a different volume for secrets and specify it in the secrets volumes. Sample for the same would be:
version: '3.4'
services:
demo_application:
image: demo_application:latest
volumes:
- /var/lib/demo_application
secrets:
- demo_secret
volumes:
- /var/lib/secrets:/demo_secret
volumes:
secrets:
How To Use Docker Secrets for Secure Credential Management?
In most of the applications, there are some sensitive data present that should not be visible to everyone for example – passwords, certificates, keys, API tokens, db cred, etc. This sensitive data should also not be stored unencrypted in the applications. All this is where Docker Secrets come into the picture – it is simply a way to store this sensitive data in the containers. It can be used to validate and authenticate users and then give them access to the applications.