Deploying Next.js

How to host a Next.js app in Production on an Ubuntu VPS

Learn how to deploy a Next.js application in a production environment on an Ubuntu VPS with this comprehensive guide. Follow step-by-step instructions to set up NGINX, PM2, and configure your Next.js app for seamless hosting.

In this guide, we'll walk through the process of hosting a Next.js app in production using NGINX and PM2. Follow these steps to get your Next.js app up and running smoothly.

If your application uses MongoDB, you can install it from here.

Step 1: Installing Necessary Packages

First, let's ensure our server has the required packages installed. Open a terminal and run the following commands:

  1. Update APT:apt update
  2. Install Nginx:apt install nginx -y
  3. This command installs the Nginx web server.

  4. Setup Node.js 21.x repository:curl -fsSL https://deb.nodesource.com/setup_21.x | sudo -E bash -
  5. Install Node.js:sudo apt-get install -y nodejs
  6. Install PM2 globally:npm install -g pm2

Step 2: Setting Up Next.js App

Now, let's prepare our Next.js app. Navigate to your project directory and execute the following commands:

npm install
npm run build
npm run start

Step 3: Configuring NGINX

Create this directory for storing access and error logs:mkdir -p /opt/nextjs/logs/

Create a new NGINX configuration file for your Next.js app. Open a text editor and paste the following configuration:

Step 4: Configuring PM2

Create an ecosystem configuration file for PM2. Open a text editor and paste the following configuration:

Step 5: Starting PM2

pm2 start ecosystem.config.js

[Optional] Using Certbot for HTTPS

Securing your Next.js application with HTTPS is crucial for protecting sensitive data and ensuring user trust.

Step 1: Install Certbot

sudo apt update
sudo apt install python3-certbot-nginx

Step 2: Obtain SSL Certificate

sudo certbot --nginx -d yourdomain.com

Step 3: Verify HTTPS Configuration

sudo nginx -t

If successful, reload NGINX:

sudo systemctl reload nginx

Step 4: Automate Certificate Renewal

sudo systemctl enable certbot.timer

Step 5: Verify Renewal

sudo certbot renew --dry-run

Conclusion

Your Next.js app is now ready and running in production with NGINX as a reverse proxy and PM2 keeping it alive.