How does a Node.js app read configuration, and why use environment variables?
BeginnerConceptNode.js builds (npm, package.json)
Answer
Short answer
Node apps read configuration from process.env — the environment variables of the process. Using environment variables means the same code (and the same Docker image) runs in dev, staging and production; only the variables change. Secrets never have to be written in code.
Example
const PORT = process.env.PORT || 3000;
const DATABASE_URL = process.env.DATABASE_URL;
if (!DATABASE_URL) { console.error("DATABASE_URL is required"); process.exit(1); }
PORT=8080 DATABASE_URL=postgres://... node server.js
docker run -e PORT=8080 -e DATABASE_URL=... shop-api:2.3.1
Local development with .env
# .env (in .gitignore — never committed)
DATABASE_URL=postgres://dev:dev@localhost:5432/shop
require("dotenv").config(); // or: node --env-file=.env server.js (Node 20.6+)
In Kubernetes
Values come from a ConfigMap (non-secret) and a Secret (passwords) via env / envFrom in the Deployment.
What to say in the interview
"Config comes from process.env, following twelve-factor. Locally we use a gitignored .env file; in Kubernetes, ConfigMaps and Secrets inject the same variable names. The app should fail fast on startup if a required variable is missing."
More on Node.js builds (npm, package.json)
What is package.json and what does it contain?BeginnerHow do you build and run a Node.js application?BeginnerWhat is the difference between npm install and npm ci?BeginnerWhy must package-lock.json be committed to Git?BeginnerWhat is the difference between dependencies and devDependencies?BeginnerWhat do the ^ and ~ symbols mean in package.json versions?Beginner