Docs / Web Servers / Setting Up a Node.js Application Behind Nginx

Setting Up a Node.js Application Behind Nginx

By Admin · Feb 25, 2026 · Updated Apr 25, 2026 · 225 views · 1 min read

Install Node.js

curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs

Deploy Your Application

cd /var/www
git clone https://github.com/yourname/myapp.git
cd myapp
npm ci --production

Run with PM2

npm install -g pm2
pm2 start app.js --name myapp
pm2 save
pm2 startup

Nginx Reverse Proxy

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
    }

    # Serve static files directly
    location /public {
        alias /var/www/myapp/public;
        expires 30d;
        access_log off;
    }
}

Enable SSL

sudo certbot --nginx -d example.com

Environment Variables

# Create .env file
NODE_ENV=production
PORT=3000
DATABASE_URL=mysql://user:pass@localhost/mydb

# Or set in PM2 ecosystem file
module.exports = {
  apps: [{
    name: "myapp",
    script: "app.js",
    env: {
      NODE_ENV: "production",
      PORT: 3000
    }
  }]
}

Why Nginx in Front?

  • SSL termination
  • Static file serving (much faster than Node.js)
  • Rate limiting and security headers
  • Load balancing across multiple Node.js instances
  • Gzip compression

Was this article helpful?