Setting Up Node.js for Production on Ubuntu
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
curl -sL https://deb.nodesource.com/setup_24.x | sudo bash -sudo apt install nodejs -yVerify:
node -vnpm -vCreate 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.
sudo npm install -g pm2pm2 start hello.jspm2 startuppm2 saveConfigure Nginx as Reverse Proxy
Nginx handles incoming traffic and forwards it to your Node.js application.
sudo apt install nginx -yCreate /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:
sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/sudo nginx -tsudo systemctl reload nginxEnable SSL with Let’s Encrypt
sudo apt install certbot python3-certbot-nginx -ysudo certbot --nginx -d yourdomain.comCertificates renew automatically.
Configure Firewall
sudo ufw allow OpenSSHsudo ufw allow 'Nginx Full'sudo ufw enableUseful PM2 Commands
pm2 list # View running applicationspm2 logs # Check application logspm2 restart all # Restart all applicationspm2 monit # Monitor resourcesTroubleshooting
Check application status:
pm2 statuspm2 logsFor 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.