Environment variables configure containers at runtime. Set them in the Dockerfile with ENV or at runtime with docker run -e. Use .env files with docker compose env_file. Containers inherit the environment from their base image plus any added with ENV or -e.
# Dockerfile ENV NODE_ENV=production ENV PORT=3000 # At runtime $ docker run -e NODE_ENV=development myapp # override ENV $ docker run -e DEBUG=true -e LOG_LEVEL=info myapp # multiple variables $ docker run --env-file .env myapp # load from .env file # docker-compose.yml services: app: environment: - NODE_ENV=production - PORT=3000
Variables set in the Dockerfile are baked into the image; variables set with -e or in Compose only exist at runtime. Environment variables are a standard way to configure apps without modifying codeāuse them for feature flags, database URLs, log levels, and other runtime settings. Compose loads variables from env_file before evaluating the environment section.