Camkode
Camkode

Deploying Next.js Apps on Ubuntu Server with Nginx and PM2

Posted by Kosal

Deploying Next.js Apps on Ubuntu Server with Nginx and PM2

In the ever-evolving landscape of web development, Next.js stands out as a powerful React-based framework that simplifies the creation of fast and scalable web applications. Combining it with PM2, a production process manager, streamlines the deployment and management process, ensuring your Next.js applications run smoothly on Ubuntu servers.

Step 1: Install Nginx

  • Update Package List
sudo apt update
  • Install Nginx:
sudo apt install nginx
  • Start Nginx
sudo systemctl start nginx
  • Enable Nginx to Start on Boot:
sudo systemctl enable nginx

Step 2: Install Node.js and npm

  • Install Node.js v20:
sudo apt-get update && sudo apt-get install -y ca-certificates curl gnupg
curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | sudo gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg
NODE_MAJOR=20
echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_$NODE_MAJOR.x nodistro main" | sudo tee /etc/apt/sources.list.d/nodesource.list
sudo apt-get update && sudo apt-get install nodejs -y

For details on Node.js installation, please visit the Installing Node.js 20 on Ubuntu: Step-by-Step Guide for a step-by-step guide.

Step 3: Install PM2 Globally

sudo npm install pm2@latest -g

Step 4: Use Git to Fetch Next.js Project from GitHub

  1. Clone Your Next.js Project:
git clone https://github.com/your-username/your-nextjs-project.git

Replace the URL with your Next.js project's GitHub repository URL.

Step 5: Run Next.js Project with PM2 and Serve with Nginx

cd your-nextjs-project
npm install
npm run build
pm2 start npm --name "nextjs-app" -- start

Replace "nextjs-app" with your desired PM2 process name.

Step 6: Configure PM2 to Start Automatically

pm2 save
pm2 startup

Follow the instructions provided by pm2 startup to set PM2 to start on boot.

Step 7: Configure Nginx to Serve the Next.js Application

  • Create Nginx Configuration File:
sudo nano /etc/nginx/sites-available/your-domain
  • Configure Nginx (Example Configuration):

    Paste the Nginx configuration:

server {
    listen 80;
    server_name your-domain.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;
    }
}

Replace your-domain.com with your actual domain or server IP address.

  • Create a Symbolic Link to Enable the Configuration:
sudo ln -s /etc/nginx/sites-available/nextjs-app /etc/nginx/sites-enabled/
  • Test Nginx Configuration:
sudo nginx -t
  • Restart Nginx to Apply Changes:
sudo systemctl restart nginx

Access your server's IP address or domain in a web browser. It should display your Next.js application served through Nginx.