skip to content

Setting Up Node.js for Production on Ubuntu

Published:

Running node app.js directly works for development, but it won’t survive server restarts or crashes. Here’s a reliable production setup using PM2, Nginx, and SSL.

Install Node.js

Terminal window
curl -sL https://deb.nodesource.com/setup_24.x | sudo bash -
sudo apt install nodejs -y

Verify:

Terminal window
node -v
npm -v

Create a Test Application

Create hello.js:

const http = require('http');
const server = http.createServer((req, res) => {
res.end('Hello World!\n');
});
server.listen(3000, 'localhost', () => {
console.log('Server running on port 3000');
});

Install PM2 Process Manager

PM2 keeps your application running, restarts it on crashes, and starts it automatically after server reboots.

Terminal window
sudo npm install -g pm2
pm2 start hello.js
pm2 startup
pm2 save

Configure Nginx as Reverse Proxy

Nginx handles incoming traffic and forwards it to your Node.js application.

Terminal window
sudo apt install nginx -y

Create /etc/nginx/sites-available/myapp:

server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}

Enable the configuration:

Terminal window
sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

Enable SSL with Let’s Encrypt

Terminal window
sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d yourdomain.com

Certificates renew automatically.

Configure Firewall

Terminal window
sudo ufw allow OpenSSH
sudo ufw allow 'Nginx Full'
sudo ufw enable

Useful PM2 Commands

Terminal window
pm2 list # View running applications
pm2 logs # Check application logs
pm2 restart all # Restart all applications
pm2 monit # Monitor resources

Troubleshooting

Check application status:

Terminal window
pm2 status
pm2 logs

For 502 errors, verify your application is running and listening on the correct port.

Summary

This setup provides a stable production environment: PM2 manages the application lifecycle, Nginx handles web traffic, SSL secures connections, and the firewall protects the server.