Hosting a Next.js App in Production with NGINX and PM2

By RoboSuperior・ Published in deployment December 21, 20243.45 min read

hosting

A Complete Guide to Hosting a Next.js App in Production with NGINX and PM2

Hosting a Next.js app in production can seem daunting, but with the right steps, you can set it up efficiently. This guide walks you through deploying your Next.js application using NGINX as a reverse proxy and PM2 as a process manager. Additionally, we'll explore how to secure your app with HTTPS using Certbot.

If your application integrates MongoDB, ensure it's installed on your server. Refer to MongoDB's installation guide if required.


Step 1: Install Required Packages

To begin, install the necessary packages. Open your terminal and run the following commands:

Update APT

  1. Update the package index to ensure your system is using the latest packages:
apt update
  1. Install NGINX Install the NGINX web server with this command:
apt install nginx -y
  1. Add Node.js 21.x Repository Add the Node.js repository to your system to install the latest version:
curl -fsSL https://deb.nodesource.com/setup_21.x | sudo -E bash -
  1. Install Node.js Install Node.js using the newly added repository:
sudo apt-get install -y nodejs

5.Install PM2 Globally Install PM2, a process manager for Node.js applications, globally:

npm install -g pm2

Step 2: Prepare Your Next.js App

Navigate to your project directory and run the following commands to prepare your app:

npm install  
npm run build  
npm run start  

These commands will install dependencies, build your app for production, and start it locally.

Step 3: Configure NGINX

Set up NGINX to serve your application as a reverse proxy.

Create a Logs Directory

Create a directory for NGINX access and error logs:

mkdir -p /opt/nextjs/logs/

Configure NGINX

Create a new configuration file for your app:

# /etc/nginx/sites-available/nextjs-app

server {
    server_name yourdomain.com;
    access_log /opt/nextjs/logs/access.log;
    error_log /opt/nextjs/logs/error.log error;

    location /_next/ {
        alias /home/youruser/.next/;
        expires 30d;
        access_log on;
    }

    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 yourdomain.com with your actual domain name and youruser with your server's username.

Enable the Configuration

Save the file and create a symbolic link to enable the configuration:

sudo ln -s /etc/nginx/sites-available/nextjs-app /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

Step 4: Set Up PM2

PM2 ensures your application stays running and restarts automatically if it crashes.

Create an Ecosystem File

Create a PM2 configuration file in your project directory:

// ecosystem.config.js

module.exports = {
  apps: [
    {
      name: 'nextjs-app',
      script: 'node_modules/.bin/next',
      args: 'start',
      cwd: '/home/youruser',
      instances: 1,
      autorestart: true,
      watch: false,
      max_memory_restart: '1G',
      env: {
        NODE_ENV: 'production',
        PORT: 3000,
        MONGO_URI: "mongodb://localhost:27017/yourdatabase",
      },
      env_production: {
        NODE_ENV: 'production',
      }
    }
  ]
};

Replace youruser and yourdatabase with your specific details.

Start the App with PM2

Run the following command to start your app:

pm2 start ecosystem.config.js

PM2 will now manage your application.

Step 5: Secure Your App with HTTPS Using Certbot

Adding HTTPS to your site increases security and user trust. Certbot simplifies this process by obtaining and configuring SSL certificates.

Install Certbot

Install Certbot and its NGINX plugin:

sudo apt update  
sudo apt install python3-certbot-nginx  

Obtain an SSL Certificate

Run the following command to obtain and configure an SSL certificate for your domain:

sudo certbot --nginx -d yourdomain.com

Follow the prompts to complete the process. Certbot will automatically configure NGINX with HTTPS.

Test the Configuration

Verify the NGINX configuration:

sudo nginx -t
sudo systemctl reload nginx

Automate Certificate Renewal

Enable automatic renewal for SSL certificates:

sudo systemctl enable certbot.timer

Test the renewal process:

sudo certbot renew --dry-run

Conclusion

Your Next.js application is now fully deployed and ready for production! With NGINX serving as a reverse proxy and PM2 ensuring stability, your app is set for optimal performance. Securing your site with HTTPS adds an extra layer of trust and security for users.

By following this guide, you can confidently deploy and host your Next.js app in a production environment.

Happy coding! 🚀

Add a new comment

Login to comment...

Comments (0)