FoundationLesson 1 of 3 in Configuration BasicsFree preview

Environment Variables

An environment variable is a name=value pair that a process carries with it. Apps read them at startup: os.environ in Python, System.getenv() in Java, process.env in Node.

export DB_HOST=db.internal     # visible to every child process from now on
PORT=9090 node server.js       # PORT is set for this one command only
echo $DB_HOST                  # db.internal

Three rules explain almost every "why is my variable empty?" bug:

  • Only exported variables reach child processes. DB_HOST=x on its own line is a shell variable; programs you start do not see it.
  • A child cannot change its parent. Running ./setenv.sh starts a new shell, sets variables there, then exits. Use source setenv.sh (or . setenv.sh) to run it in your current shell.
  • Every value is a string. DEBUG=false arrives as the text "false", which is truthy in most languages. Parse it explicitly.

A .env file is just a text file. Nothing loads it unless your tool does (Docker Compose, a dotenv library, systemd's EnvironmentFile=).

To inspect a running process on Linux, read /proc/<pid>/environ. Handy for debugging, and a reminder that env vars are not a vault.

In interviews: "How does a container get its database URL?" Through environment variables (docker run -e, a Compose environment: block, a Kubernetes env: list), so the same image runs everywhere.

Practice

Solve 3 of 4 to complete this lesson.

0/4 solved

Solve 3 more to complete this lesson, or move on and come back later.

Skip to next: Twelve Factor Config