Skip to content

Secrets and Environment variables

Cisco edited this page Sep 28, 2025 · 1 revision

Docker Secrets

  • not exposed as environment variables
  • accessed from memory-only filesystem at /run/secrets
    • one file per secret
  • only services granted access can read them

Standalone container

  • mount a folder with secrets docker run -d -v $(pwd)/secrets:/run/secrets <image>

Docker Swarm

  • create echo "<secret>" | docker secret create <secret_name> -
  • deploy a service using the secret `docker service create --name --secret <secret_name>
  • access the secret cat /run/secrets/<secret_name>

Envsubst

  • part of gettext
  • insert dynamic vars from environment into text files such as config files
  • envsubst [opt] [shell format]
  • benefits : don't duplicate config files (one for each environment)
# limit substitution to specified variables
# useful when some vars should be defined later
envsubst '$USER' < input.txt

# usage for a config file
# have a config template with vars in $syntax
# output an updated config file
envsubst '$VAR1 $VAR2' < config.template > config.conf

Best practices

  • use '' around vars to prevent premature expansion by shell
  • handle undefined vars
    • default values in bash : export API_KEY=${API_KEY:-defaultkey}
    • explicit check "${API_KEY:?undefined API_KEY}"
  • check result envsubst < config.template
  • validate config with nginx -t

Sources

https://blog.stephane-robert.info/docs/outils/projets/envsubst/

Clone this wiki locally