Deploying a Node.js App with PM2 and Nginx on Ubuntu
Deploying Node.js applications in production requires more than just running node app.js
. You need process management, auto-restarts, and a way to serve your app securely over HTTP/HTTPS. In this guide, you'll learn how to deploy a Node.js app on Ubuntu using PM2 for process management and Nginx as a reverse proxy.
Why Use PM2 and Nginx?
- PM2: Keeps your Node.js app running, restarts it if it crashes, and makes startup on reboot easy.
- Nginx: Handles incoming web traffic, SSL, and can serve static files or load-balance multiple Node.js processes.
Step 1: Prepare Your Ubuntu Server
sudo apt update
sudo apt upgrade -y
Step 2: Install Node.js and npm
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
node -v
npm -v
Step 3: Clone Your Node.js App
git clone https://github.com/yourusername/your-node-app.git
cd your-node-app
npm install
Step 4: Install and Use PM2
sudo npm install -g pm2
pm2 start app.js --name "my-app"
pm2 status
pm2 logs my-app
To start your app on server reboot:
pm2 startup
pm2 save
Step 5: Install and Configure Nginx
sudo apt install nginx
sudo systemctl enable nginx
sudo systemctl start nginx
Edit or create a new site config:
sudo nano /etc/nginx/sites-available/my-app
Example Nginx config for a Node.js app running on port 3000:
server {
listen 80;
server_name yourdomain.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_cache_bypass $http_upgrade;
}
}
sudo ln -s /etc/nginx/sites-available/my-app /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx
Step 6: (Optional) Enable HTTPS with Let's Encrypt
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com
Certbot will automatically update your Nginx config for SSL.
Step 7: Test Your Deployment
- Visit http://yourdomain.com (and https://yourdomain.com if using SSL).
- Your Node.js app should be live, managed by PM2, and fronted by Nginx!
Conclusion
With PM2 and Nginx, deploying Node.js apps on Ubuntu is reliable, scalable, and production-ready. PM2 keeps your app running, while Nginx provides SSL, reverse proxying, and static file serving. This stack is a proven choice for startups and enterprises alike.
Need help or want a custom deployment script? Contact me!