Deploying a Node App: Environment Variables and PM2

Site Admin · 11 Sep 2026 · 9 views

Deploying a Node App: Environment Variables and PM2

A deploy-ready app reads its configuration from the environment, runs with a process manager, and logs clearly. This lesson covers the essentials: env vars and PM2.

Environment variables

Secrets and settings never belong in code. Read them from process.env:

const PORT = process.env.PORT || 3000;
const dbUrl = process.env.MONGODB_URL;

app.listen(PORT);

The hosting platform sets these values, so the same code runs locally and in production with different config.

Managing env files

During development, the dotenv package loads a .env file. Add .env to .gitignore so keys never reach the repository, and commit an example file instead. Install with npm install --save dotenv, then import it at the top of your entry file:

import 'dotenv/config';

PM2 basics

PM2 keeps a production Node process alive, restarts it after crashes, and restarts it on reboot:

npm install -g pm2
pm2 start src/index.js --name my-app

Useful commands:

pm2 status
pm2 logs
pm2 restart my-app
pm2 save

pm2 save freezes the process list so pm2 startup can restore it after the server reboots.

Logging

Console output is enough for plain Node apps. PM2 captures stdout and stderr and rotates or forwards logs. Consider a logging library when you need structured, queryable entries.

Key Points

  • Environment variables separate config from code.
  • dotenv loads .env in development.
  • Never commit real secrets or .env files.
  • PM2 runs, monitors, and restarts processes.
  • pm2 save and startup survive server reboots.
Share this post:

Comments (0)

Please login or register to comment.