Deploying a Next.js Project on Ubuntu 20 with Nginx

This documentation provides detailed, step-by-step instructions for deploying the Lavander Next.js project on an Ubuntu 20 server, using Nginx as a reverse proxy.

  1. Update and Upgrade the System

Run the following commands to ensure your system is up-to-date:

sudo apt update && sudo apt upgrade -y

 

  1. Install Node.js and npm

Install Node.js using nvm (Node Version Manager):

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash

source ~/.bashrc

nvm install --lts

Verify installation:

node -v

npm -v

 

  1. Get the Source Code or full Next.js project:

You can either:

a) Clone the repository using git:

git clone <your-repository-url>

cd <project-directory>

OR

b) Manually upload the source files (the complete Next.js project) to the server using tools such as SFTP or SCP.

 

  1. Install Dependencies and Build the Project

Navigate to the project directory, install dependencies, and build the project:

cd <project-directory>

npm install

npm run build

 

  1. Use PM2 to Run the Application

Install PM2 globally and start your application:

npm install -g pm2

pm2 start npm --name "nextjs-app" -- start

Save the PM2 process list and set up PM2 as a service to start on boot:

pm2 save

pm2 startup

 

Follow the instructions displayed by PM2 to enable it as a service. For example:

sudo env PATH=$PATH:/usr/bin pm2 startup systemd -u <your-username> --hp /home/<your-username>

 

  1. Install and Configure Nginx

Install Nginx:

sudo apt install nginx -y

Configure Nginx as a reverse proxy. Edit the configuration file:

sudo nano /etc/nginx/sites-available/default

 

Add the following 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;

}

}

 

Test the configuration and restart Nginx:

sudo nginx -t

sudo systemctl restart nginx

 

  1. Configure Firewall

Allow HTTP and HTTPS traffic through the firewall:

sudo ufw allow 'Nginx Full'

sudo ufw enable

 

  1. Optional: Set Up SSL with Let's Encrypt

Install Certbot and obtain an SSL certificate:

sudo apt install certbot python3-certbot-nginx -y

sudo certbot --nginx -d your-domain.com -d www.your-domain.com

Verify auto-renewal:

sudo certbot renew --dry-run

 

  1. Verify Deployment

Visit your domain in a web browser to verify that your Next.js application is running successfully.