Setting Up a Node.js Application for Production on Ubuntu 22.04
This guide covers setting up a Node.js application for production, using PM2 for application management and Nginx as a reverse proxy for secure access.
Prerequisites
Before starting, ensure you have: a configured Ubuntu 22.04 server, a domain name pointing to your server, Nginx with SSL via Let's Encrypt, and Node.js installed.
Step 1 — Creating a Node.js Application
Create a basic Node.js app that returns "Hello World" for HTTP requests. Use this example to test your setup before deploying your own application.
const http = require('http');
const hostname = 'localhost';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World!\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Step 2 — Installing PM2
Install PM2 globally to manage your Node.js app processes, ensuring they automatically restart after crashes or server reboots.
sudo npm install pm2@latest -g
Start your application with PM2:
pm2 start hello.js
Configure PM2 to auto-start on server boot:
pm2 startup systemd
Step 3 — Setting Up Nginx as a Reverse Proxy Server
Configure Nginx to direct web traffic to your Node.js application, enabling secure HTTPS access.
server {
...
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_cache_bypass $http_upgrade;
}
...
}
Conclusion
Your Node.js application is now running behind an Nginx reverse proxy on Ubuntu 22.04, ready for production use.