Environment variable

4 snippets across 3 stacks - Docker, Bash & Linux, Python

DKDocker

Environment Variables (-e)

DK · Run Options
Syntax
docker run -e <KEY>=<value> <image>
docker run --env-file <file> <image>
Example
docker run -e NODE_ENV=production -e DB_HOST=db myapp:1.0
docker run --env-file .env myapp:1.0

Note Using --env-file keeps secrets out of your shell history and process list. Each line in the file should be KEY=value with no quotes needed around the value.

ENV - Set Environment Variables

DK · Dockerfile
Syntax
ENV <key>=<value> [<key>=<value>...]
Example
ENV NODE_ENV=production
ENV APP_PORT=3000 LOG_LEVEL=info

Note ENV values persist into the running container and into child images. If you only need a variable during build time (e.g., a version number), use ARG instead to avoid leaking it into the final image.

SHBash & Linux

Environment Variables

SH · System Info
Syntax
env
export VAR=value
printenv VAR
Example
env | grep PATH
export DATABASE_URL='postgres://user:pass@db:5432/mydb'
printenv HOME
Output
/home/deploy

Note env lists all environment variables. export makes a variable available to child processes. Variables set without export are local to the current shell. printenv retrieves a single variable. Avoid putting secrets in environment variables on shared systems; prefer a secrets manager.

PYPython

os and os.path

PY · Common Standard Library
Syntax
import os
os.path.join()
os.environ
Example
import os

# Environment variables
db_host = os.environ.get("DB_HOST", "localhost")
print(f"DB: {db_host}")

# Path operations (prefer pathlib for new code)
print(os.path.expanduser("~"))
print(os.path.splitext("report.pdf"))
print(os.getcwd())
Output
DB: localhost
/Users/username
('report', '.pdf')
/current/directory

Note Prefer pathlib.Path for path manipulation in new code. os.environ provides direct access to environment variables. Use os.getenv() for safe access with defaults.

Frequently asked questions

How does Docker handle environment variable?
This task is covered in 3 stacks on this page: Docker, Bash & Linux, Python. The "Environment Variables (-e)" snippet in Docker uses `docker run -e <KEY>=<value> <image>`.
Which command does the Docker example use?
The "Environment Variables (-e)" snippet uses `docker run -e <KEY>=<value> <image>`, from the Run Options section of the Docker cheat sheet.
Which stacks cover "environment variable" on this page?
Docker, Bash & Linux, Python. Together they hold 4 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Environment Variables (-e)": Using --env-file keeps secrets out of your shell history and process list. Each line in the file should be KEY=value with no quotes needed around the value.