Passing secrets to a Dockerfile
Tue 15 March 2022 Category: Misc. Tags: [docker] [security]Problem
You want to safely use a secret inside a Dockerfile. This secret may be stored in an environment varialbe or a text file.
Using the ARG
instruction in the Dockerfile is not safe because everyone can see these values using the docker history <image>
command. One possible workaround is to use multistage builds but this can be complicated and result in increased build times (it’s not recommended).
NOTE: We are not talking about runtime secrets that are passed to the containers but secrets to be used only for the image building.
Solution
The simplest way to safely use secrets inside a Dockerfile is to use the docker build option `—secret“`, available in docker version 2.10.0 and later using the new BuildKit backend.
There are two ways to use the --secret
option.
Don’t forget to activte the BuildKit option setting DOCKER_BUILDKIT=1
in your terminal’s environment.
1. Using a text file for the secret
The secret is stored in a text file called secret_file.txt
docker image build --secret id=mysupersecret,src=secret_file.txt .
2. Using an environment variable for the secret
The secret is stored in an environment variable called SECRET_VAR
docker image build --secret id=mysupersecret,env=SECRET_VAR .
If you don’t mind using the same name for the secret-id and the environemnt variable you can ommit the env option like this:
docker image build --secret id=SECRET_VAR .
About docker-compose
Although docker-compose supports the use of BuildKit, passing secrets inside the Dockerfile with the approach described above is not supported (yet).