Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

2. How to Deploy Backend Code in Production

Lesson 2 of 23 in the free Backend Development notes on Siksha Sarovar, written by Rohit Jangra.

What is Deployment?

Deployment is the process of making your backend application available on the internet so that real users can access it. During development you run your server locally on localhost:5000, but in production it needs to run on a server with a public IP address, 24/7, with automatic restarts on crashes, HTTPS support, and process management.

---

Deployment Platforms Comparison

PlatformTypeFree TierAuto-DeployBest For
RenderPaaSYes (sleeps after inactivity)Yes (GitHub)Node.js, hobby projects
RailwayPaaSYes ($5 credit/month)Yes (GitHub)Modern MERN apps
HerokuPaaSNo (paid from Nov 2022)YesLegacy projects
AWS EC2IaaS12 months free tierManual / CI-CDEnterprise, full control
VPS (DigitalOcean/Linode)IaaSNoManual / CI-CDProduction with full control
VercelServerlessYesYes (GitHub)Serverless functions only
For beginners, Render or Railway are the easiest starting points. For production-grade apps with full control, a VPS (like DigitalOcean Droplet) with PM2 + Nginx is the industry standard.

---

PM2 — Node.js Process Manager

PM2 ensures your Node.js server keeps running even after crashes, server reboots, or unhandled exceptions. It also provides process monitoring, log management, and cluster mode for multi-core CPUs.

Installation:

npm install -g pm2

Common PM2 commands:

pm2 start src/index.js --name "my-backend"   # Start app
pm2 start ecosystem.config.js                 # Start using config file
pm2 stop my-backend                           # Stop app
pm2 restart my-backend                        # Restart app
pm2 delete my-backend                         # Remove from PM2 list
pm2 logs my-backend                           # View logs
pm2 logs my-backend --lines 50                # Last 50 log lines
pm2 status                                    # See all processes
pm2 monit                                     # Real-time monitoring dashboard
pm2 startup                                   # Generate startup script (auto-start on reboot)
pm2 save                                      # Save current process list

Cluster mode (uses all CPU cores):

pm2 start src/index.js -i max  # max = number of CPU cores

---

Nginx as a Reverse Proxy

Nginx sits in front of your Node.js app. It handles incoming traffic on port 80 (HTTP) and 443 (HTTPS), and forwards requests to your Node.js server running on port 5000. This setup provides: SSL termination, load balancing, serving static files, request buffering, and rate limiting.

Basic Nginx config (/etc/nginx/sites-available/myapp):

server {
    listen 80;
    server_name api.myapp.com;

    location / {
        proxy_pass http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

Enable and test: sudo nginx -t && sudo systemctl reload nginx

---

HTTPS with Let's Encrypt (Certbot)

sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d api.myapp.com
# Certbot automatically edits nginx config to add SSL
# Auto-renewal: sudo certbot renew --dry-run

---

Environment Variables in Production

Never use .env files in production directly on a server where the file could be read. Instead:

  • Render / Railway / Heroku: Set env vars through the dashboard UI
  • VPS: Use export VAR=value in the PM2 ecosystem config
  • Docker: Use --env-file flag or Docker Compose env_file option

---

CI/CD with GitHub Actions

Continuous Integration / Continuous Deployment automates testing and deployment on every push.

# .github/workflows/deploy.yml
name: Deploy to Production
on:
  push:
    branches: [main]
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: SSH and Deploy
        uses: appleboy/ssh-action@master
        with:
          host: ${{ secrets.HOST }}
          username: ${{ secrets.USERNAME }}
          key: ${{ secrets.SSH_KEY }}
          script: |
            cd /var/www/myapp
            git pull origin main
            npm install
            pm2 restart ecosystem.config.js

---

Docker Introduction

Docker packages your application and all its dependencies into a portable container that runs identically on any machine — your laptop, your colleague's machine, or a production server.

  • Dockerfile: Blueprint for building a Docker image
  • docker-compose.yml: Define and run multi-container applications (app + MongoDB + Redis)

---

Zero-Downtime Deployment Strategies

StrategyDescription
PM2 cluster reloadpm2 reload app — restarts workers one by one
Blue-Green deploymentTwo identical environments; switch traffic after testing
Rolling deploymentUpdate one instance at a time in a cluster
Canary deploymentRoute 5% of traffic to new version, gradually increase

For most Node.js backends with PM2, pm2 reload ecosystem.config.js achieves zero-downtime restarts by gracefully handling ongoing requests before restarting each worker.