MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Production Configuration, Environment Variables & PM2 Process Manager0%
Study Materials
Node.js & Express.jsProgress 0%
1.1Node.js Architecture, V8 Engine & Single-Threaded Event Loop1.2Call Stack, Callback Queue, Microtask Queue & Libuv Workers1.3Non-Blocking Asynchronous Code with Promises and Async/Await
5.1Input Validation & Data Sanitization with Joi or Zod5.2User Authentication with JWT (JSON Web Tokens) & HTTP-Only Cookies5.3Password Hashing with Bcrypt & Role-Based Access Control (RBAC)5.4Security Hardening: Helmet, CORS, Express Rate Limiting & HPP5.5Production Configuration, Environment Variables & PM2 Process Manager
HomeTutorialsNode.js & Express.jsProduction Configuration, Environment Variables & PM2 Process Manager

Production Configuration, Environment Variables & PM2 Process Manager

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

Running node server.js in a terminal is fine for local testing, but deploying a raw command in production means the moment an uncaught exception occurs or the server machine restarts, your entire website goes offline. Professional Node.js production environments require environment configuration management, graceful shutdown handling, and a process manager like PM2.


1. Managing Environment Variables (dotenv)

Never hardcode database connection strings, API secrets, or ports in code:

1# .env (NEVER commit to Git! Add to .gitignore)
2PORT=5000
3NODE_ENV=production
4DATABASE_URL=mongodb+srv://admin:secret@cluster0.mongodb.net/prod_db
5JWT_SECRET=c8d48291a9b24479e0f2b380d6b99
6CORS_ORIGIN=https://mskinstitute.com

Load environment variables at the absolute entry point of your server:

1import 'dotenv/config';
2 
3const port = process.env.PORT || 5000;
4console.log(`Running in ${process.env.NODE_ENV} mode on port ${port}`);

2. Why PM2 (Process Manager 2)?

PM2 is the production runtime process manager for Node.js:

  • Zero-Downtime Reloads: Reloads updated code without dropping a single active client connection.
  • Cluster Mode: Automatically spawns worker processes across all available CPU cores, bypassing the single-threaded limit!
  • Automatic Restarts: Instantly revives dead worker instances upon crashes or memory leaks.
  • System Startup Hook: Configures systemd/init scripts so the application reboots automatically if the server machine restarts.

3. Configuring PM2 with ecosystem.config.cjs

1module.exports = {
2 apps: [
3 {
4 name: 'msk-backend-api',
5 script: './src/server.js',
6 instances: 'max', // Spawns 1 process per CPU core!
7 exec_mode: 'cluster',
8 autorestart: true,
9 watch: false, // Do NOT watch files in production
10 max_memory_restart: '1G', // Restart worker if memory exceeds 1 GB
11 env_production: {
12 NODE_ENV: 'production',
13 PORT: 5000
14 }
15 }
16 ]
17};

4. Essential PM2 CLI Commands

1# Start application in cluster mode using configuration
2pm2 start ecosystem.config.cjs --env production
3 
4# View real-time cluster status and memory usage
5pm2 status
6 
7# Real-time streaming log viewer
8pm2 logs msk-backend-api
9 
10# Zero-downtime rolling code reload
11pm2 reload msk-backend-api
12 
13# Generate OS system startup script
14pm2 startup
15pm2 save

Interactive Quiz• Knowledge Check

Multiple Choice Questions

Question 1
What is the primary benefit of running PM2 in cluster mode with instances: 'max'?
Question 2
Why should the .env file containing secrets never be committed to a public or team Git repository?
Question 3
What command configures PM2 to automatically revive all registered applications upon server machine reboot?
Question 4
What is the advantage of pm2 reload over pm2 restart during a production deployment?
Question 5
What does the max_memory_restart: '1G' setting in PM2 do?

Related Lessons

Previous LessonNext Lesson
Security Hardening: Helmet, CORS, Express Rate Limiting & HPPNone

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Node.js & Express.js with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
Previous
PreviousPrevNext