Deploying Next.js on ProDomain VPS
This guide walks you through deploying a production-ready Next.js application using the App Router. We will use a standard Linux environment with Node.js, PM2 for process management, and Nginx as a reverse proxy.
Prerequisites
1. A **Cloud VPS** instance (Ubuntu 22.04 LTS recommended).
2. Root or sudo access.
3. A domain name pointing to your VPS IP.
Step 1: Environment Setup
First, update your system and install the required build tools.
sudo apt update && sudo apt upgrade -y
sudo apt install curl git build-essential -yInstall Node.js (LTS)
We recommend using NodeSource for the latest stable Node.js version.
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejsVerify the installation:
node -v
npm -vStep 2: Clone & Build Your App
Navigate to your web directory and clone your repository.
mkdir -p /var/www/my-app
cd /var/www/my-app
git clone https://github.com/yourusername/your-repo .
npm install
npm run buildStep 3: PM2 Process Management
PM2 keeps your application running in the background and restarts it if it crashes.
sudo npm install -g pm2
pm2 start npm --name "nextjs-app" -- start
pm2 save
pm2 startupStep 4: Nginx Reverse Proxy
Install Nginx to handle incoming traffic and SSL termination.
sudo apt install nginxCreate a new configuration file:
server {
listen 80;
server_name example.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;
}
}Link the configuration and restart Nginx:
sudo ln -s /etc/nginx/sites-available/my-app /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginxSecurity Best Practices
- **Firewall**: Ensure ufw allows ports 80, 443, and 22.
- **SSL**: Use Certbot to obtain a free Let's Encrypt certificate.
- **Updates**: Regularly run `npm audit` and system updates.
- 2024-03-15—Initial or baseline update for this page.