Docker ContainerDevOps GuidesDevSecOpsDocker Guide

Article & Tutorial

Docker Environment Variables and Secrets Explained

Learn Docker environment variables and secrets, including docker run -e, env files, Compose environment, secret risks, examples, and best practices.

Contents

Docker Environment Variables and Secrets Explained

Docker environment variables help configure containers at runtime. This guide explains -e , env files, Docker Compose environment values, secret risks, and safer practices.

Why environment variables are used

Applications often need runtime configuration such as port, API URL, database host, feature flags, or log level. Environment variables let you change configuration without rebuilding the image.

Run with one variable

docker run -e NODE_ENV=production myapp:1.0

Run with multiple variables

docker run -d --name app \ -e NODE_ENV=production \ -e API_BASE_URL= \ myapp:1.0

Use an env file

# app.env NODE_ENV=production API_BASE_URL=

docker run --env-file app.env myapp:1.0

Compose environment example

services: app: image: myapp:1.0 environment: NODE_ENV: production API_BASE_URL:

Secrets warning

Bad example

docker run -e DB_PASSWORD=SuperSecretPassword myapp:1.0

This may be acceptable only in a local test environment. For production, use your orchestrator, CI/CD secret store, cloud secret manager, or Docker/Kubernetes secret features.

Common values

  • Variable — Use
  • NODE_ENV — Runtime mode
  • DATABASE_HOST — Database location
  • LOG_LEVEL — Logging verbosity
  • PORT — Application port

Common mistakes

  • Hardcoding secrets in Dockerfiles.
  • Committing .env files with passwords.
  • Printing variables in logs.
  • Using the same secret across all environments.
  • Putting production secrets in local Compose files.

Best practices

  • Use environment variables for non-sensitive runtime configuration.
  • Use secret stores for sensitive values.
  • Add .env to .gitignore when it contains local values.
  • Separate dev, staging, and production values.
  • Rotate exposed credentials immediately.

Related Melochip guides

  • Docker Learning Path
  • GitLab Variables and Secrets
  • Docker Compose Beginner Guide

Official references

  • Docker Compose environment variables

Did this help?

Yes No

Join the discussion

0 Comments

Ask questions, add context, or share what worked.

Sign in to join the discussion

No comments yet. Start the discussion.

More from Melochip Editorial

Related articles

Stay in the loop. Get new Melochip articles

Receive Melochip article updates when new articles are available. Explicit opt-in only.

No pre-checked boxes. Unsubscribe support is part of the subscriber foundation.