How To Deploy and install a Next.js App or Website in a production environment on Ubuntu Server

This guide explores how to effectively deploy and install a Next.js application or website in a production environment using NGINX as a reverse proxy and PM2 for process management.

By following these detailed steps, you can ensure your Next.js app runs smoothly and efficiently.

Step 1: Installing Required Packages, necessary for NextJs Production

First, let's make sure our server is up to date and has all required packages/applications installed.

Open Terminal(SSH with root level permission) and run the following commands in sequential order:-

1. Update Ubuntu:

sudo apt update
It updates the local package list with the latest versions and information from configured repositories.

2. Upgrade Ubuntu:

sudo apt upgrade -y

It automatically installs the latest versions of installed packages, answering "yes" to all prompts during the process.

3. Install Nginx (Web Server):

apt install nginx -y

This command will install Webserver on your server, to serve your website/app to your users.

4. Setup Node.js 21.x repository:

curl -fsSL https://deb.nodesource.com/setup_21.x | sudo -E bash -

This command downloads and executes the script to add the Node.js 21.x repository to your system.

5. Install Node.js on Server:

sudo apt-get install -y nodejs

It will install node.js on your server using the repository we added through the previous command.

You can use the " node " command to check node is installed correctly or not.

6. Install PM2 Globally on Server:

npm install -g pm2

This command globally installs the PM2 process manager using npm.

Step 2: Configure Nginx Webserver

Create the directory for your project files.

mkdir /var/www/domain.com

Let's create a new Nginx Configuration for your Next.js app/website.

vi /etc/nginx/sites-enabled/domain.com.conf

In this command we are using vi editor to create a config file so you can use " i " to start editing, " esc " to exit from editing and " :wq " to write the file.

Copy the below code in the config file:

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

Delete the default configuration file.

sudo rm /etc/nginx/sites-enabled/default

Now let's restart the Nginx server, so our changes can happen immediately.

sudo service nginx restart

Step 3: Setting Up Next.js App/Web

Next, let's set up your Next.js app. Navigate to your project directory and run the following commands:

cd /var/www/domain.com

Move to working directory

Upload or create your project files here using any FTP client, then run the below command to make the Next.js app

npm install
npm run build

These commands will initialize node packages and run the next build to create build files.

Step 4: Configuring Process Manager - PM2

Create a PM2 ecosystem configuration file by opening a text editor and pasting the following configuration:

vi ecosystem.config.js
module.exports = {
  apps: [
    {
      name: 'domain.com',
      script: 'node_modules/.bin/next',
      args: 'start',
      cwd: '/var/www/domain.com',
      instances: 1,
      autorestart: true,
      watch: false,
      max_memory_restart: '2G',
      env: {
        NODE_ENV: 'production',
        PORT: 3000,
        NEXT_PUBLIC_URL: "https://domain.com",
        NEXTAUTH_URL: "https://domain.com",
        NEXTAUTH_SECRET: "sdf",
      },
      env_production: {
        NODE_ENV: 'production'
      }
    }
  ]
};

You can configure it according to you needs, like you can change ram size from 2G to your required config.

Step 5: Starting Process Manger - pm2

Start your Next.js app with PM2 by executing the following command in your project directory:

pm2 start ecosystem.config.js

It will start pm2 in the background by default.

pm2 startup

It will create a startup script for the process manager that will handle server crashes or reboots so your app/web doesn't go offline on reboot.

pm2 save

It updates the in-memory PM2

Some basic pm2 commands: it's not required for setup

pm2 ls
pm2 stop domain.com
pm2 start domain.com
pm2 restart domain.com

You can check the PM2 official site for more commands.

Step 6: Auto SSL using Certbot for HTTPS [Optional]

Securing your Next.js application with HTTPS is essential for safeguarding sensitive data and maintaining user trust. Certbot, a popular tool from the Let's Encrypt Certificate Authority, simplifies obtaining and managing SSL/TLS certificates. Follow these steps to configure HTTPS for your Next.js app using Certbot:-

Step A: Install Certbot on the server

sudo apt update
sudo apt install python3-certbot-nginx

Step B: Issue SSL Certificate

sudo certbot --nginx -d domain.com

Follow the prompts to enter your email address for renewal reminders and agree to the terms of service. Certbot will take care of issuing the certificate and configuring NGINX for you.

Step C: Verify HTTPS Configuration

sudo nginx -t

If the test is successful, it will reload NGINX to apply the changes:

sudo systemctl reload nginx

Step D: Automate Certificate Renewal (AutoSSL)

sudo systemctl enable certbot.timer

It will make sure to renew your SSL timely and will also replace any damaged or invalid certificates with valid ones automatically without you worrying about it and the best thing is it's completely free.

Step E: Verify Renewal

sudo certbot renew --dry-run

If the dry run finishes without errors, you're all set. Certbot will automatically manage certificate renewals as needed.

Important Notes:

  • Replace domain.com with your domain name
  • Ubuntu version greater than 18

Conclusion

Your Next.js app is now fully deployed and running in production! NGINX is acting as a reverse proxy, forwarding requests to your Next.js server, while PM2 ensures your app remains operational.

With these steps and configurations, you've successfully deployed and hosted your Next.js application in a production environment.

Vivek Singh

Vivek Singh

Vivek Singh Born on 20 April 1998 from Bhopal is an Youngest Entrepreneur and Bussinesman. ( C.E.O of RedLake )

Comments (0)

Comment