Introduction
Deploying a Node.js application to production requires proper server configuration, process management, reverse proxy setup, and SSL configuration. This guide explains how to deploy a Node.js application on a production VPS using Ubuntu, NGINX, and PM2.
Server Requirements
- Ubuntu 22.04 LTS VPS
- Minimum 2 vCPU and 4GB RAM
- Root or sudo access
- Domain pointed to server IP
Step 1: Update Server
sudo apt update && sudo apt upgrade -y
Step 2: Install Node.js
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt install -y nodejs
Verify installation:
node -v
npm -v
Step 3: Install PM2 Process Manager
sudo npm install -g pm2
PM2 keeps your application running and restarts it automatically if it crashes.
Step 4: Upload or Clone Your Application
git clone https://github.com/your-repository.git
cd your-repository
npm install
Start the application:
pm2 start app.js --name node-app
pm2 save
pm2 startup
Step 5: Install and Configure NGINX
Install NGINX:
sudo apt install nginx -y
Create configuration file:
sudo nano /etc/nginx/sites-available/nodeapp
Add reverse proxy configuration:
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;
}
}
Enable configuration:
sudo ln -s /etc/nginx/sites-available/nodeapp /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
Step 6: Enable SSL
Install Certbot:
sudo apt install certbot python3-certbot-nginx -y
Run SSL configuration:
sudo certbot --nginx -d yourdomain.com
Your Node.js application is now accessible over HTTPS.
Security Recommendations
- Disable root SSH login
- Use SSH key authentication
- Enable UFW firewall
- Install Fail2Ban
- Keep server updated regularly
Performance Optimization Tips
- Use PM2 cluster mode for multi-core support
- Enable gzip compression in NGINX
- Monitor CPU and memory usage
- Use CDN for static assets
Conclusion
Deploying a Node.js application on a production VPS requires proper configuration of the runtime environment, reverse proxy, and SSL. Following this structured setup ensures security, scalability, and performance for production workloads.