In your examples the environment variables are being set from secrets, but just for that process.
If you want run time environment variables to be set from secrets, you'll need to either mount a volume containing the secrets, or pass the secrets via docker-compose, in either case, then utilize an entrypoint script to set the secrets based on secrets locations.
Note: the secret files will need to be available to anyone/service that will be running the dockerfile.
Add an entrypoint script to your Dockerfile
Dockerfile:
FROM alpine
# Bash is needed for the script to set env_vars based on secrets
RUN apk upgrade --update-cache --available && \
apk add bash \
&& rm -rf /var/cache/apk/*
# Adding entrypoint script to image
COPY ./docker_entrypoint /usr/local/bin/docker_entrypoint
RUN chmod +x /usr/local/bin/docker_entrypoint
ENTRYPOINT [ "docker_entrypoint"]
CMD ["printenv"]
This script will look for an environment variables with the format ENVAR_FILE to find the path of where the secret is being stored - export the secret to an environment variable without the _FILE, and then call the remaining command.
docker_entrypoint:
#!/usr/bin/env bash
set -e
file_env() {
local var="$1"
local fileVar="${var}_FILE"
local def="${2:-}"
if [ "${!var:-}" ] && [ "${!fileVar:-}" ]; then
echo >&2 "error: both $var and $fileVar are set (but are exclusive)"
exit 1
fi
local val="$def"
if [ "${!var:-}" ]; then
val="${!var}"
elif [ "${!fileVar:-}" ]; then
val="$(< "${!fileVar}")"
fi
export "$var"="$val"
unset "$fileVar"
}
# Explicitly list the environment variables you want to
# set from secrets
file_env "ENVAR1"
file_env "ENVAR2"
exec "$@"
Now you could pass environment variables of the format ENVAR_FILE=/mnt/path/to/secret - and the above entrypoint script will read the contents of that file and generate the variables ENVAR=whateverYourSecretIs
An example using docker-compose:
services:
someService:
image: <imageFromDockerFileAbove>
environment:
- ENVAR1_FILE=/run/secrets/envar1
- ENVAR2_FILE=/run/secrets/envar2
secrets:
- envar1
- envar2
secrets:
envar1:
file: /pth/to/secret
envar2:
file: /pth/to/secret
Expected output:
someService_1 | HOSTNAME=<containerID>
someService_1 | ENVAR1=mysecret1
someService_1 | ENVAR2=mysecret2
someService_1 | PWD=/
someService_1 | HOME=/root
someService_1 | SHLVL=0
someService_1 | PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
And
docker inspect --format='{{json .Config.Env}}' <containerID>
returns:
["ENVAR1_FILE=/run/secrets/envar1","ENVAR2_FILE=/run/secrets/envar2","PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"]