Howto use a docker/swarm secret value as an environment variable in "docker service create"?
I need to write scripts that create services on docker swarm clusters. An example script would be simiar to this:
docker service create \
--name postgres \
--mode global \
--constraint "node.labels.postgres==master" \
--network my-network \
--env POSTGRES_USER="postgres" \
--env POSTGRES_PASSWORD="****" \
postgres:10
The POSTGRES_USER and POSTGRES_PASSWORD environment variables should come from docker secrets. For example:
echo "example_password" | docker secret create postgres-password -
I understand that the secret can be accessed as a file from inside a running container. But in the a above example, it must be passed to the "service create" command as an environment variable. It is used by the entry point of the container, so it must be presented BEFORE the container is created. So how can I pass a secret to the --env switch of the "docker service create" command?
Solution 1:
As stated here https://github.com/docker-library/docs/blob/master/postgres/README.md you may use swarm secrets in postgres service when if you add _FILE suffix like:
docker service create \
--name postgres \
--mode global \
--constraint "node.labels.postgres==master" \
--network my-network \
--secret "postgres-password" \
--env POSTGRES_USER="postgres" \
--env POSTGRES_PASSWORD_FILE="/run/secrets/postgres-password" \
postgres:10
If you ask about generic solution for any service, it's not possible without creating container or service, which exposes passwords in clear text (say Nginx which reads passwords from files that are secrets)