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.
Prerequisites
- A VPS running Ubuntu (20.04 or later)
- Node.js and npm installed
- A Next.js application ready for deployment
- Basic knowledge of the command line and SSH
- A domain name (optional, but recommended for production)
- A basic understanding of NGINX and PM2
Step 1: Installing Necessary Packages
First, let's ensure our server has the required packages installed. Open a terminal and run the following commands:
Advertisement
sudo apt update
Install nginx:
sudo apt install nginx -y
This command installs Nginx web server.
Setup Node.js 21.x repository:
Advertisement
curl -fsSL https://deb.nodesource.com/setup_21.x | sudo -E bash -
This command downloads and runs the script to add the Node.js 21.x repository to your system.
Install Node.js:
sudo apt-get install -y nodejs
This command installs Node.js using the newly added repository.
Advertisement
Install PM2 globally:
npm install -g pm2
This command installs PM2 process manager globally using npm.
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:
Advertisement
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:
# /etc/nginx/sites-available/nextjs-example.willandskill.eu
server {
server_name yourdomain.com;
access_log /opt/nextjs/logs/access.log;
error_log /opt/nextjs/logs/error.log error;
location /_next/ {
alias /home/nextapp/.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;
}
}
Step 4: Configuring PM2
Create an ecosystem configuration file for PM2. Open a text editor and paste the following configuration:
Advertisement
// ecosystem.config.js
module.exports = {
apps: [
{
name: 'my-nextjs-app',
script: 'node_modules/.bin/next',
args: 'start',
cwd: '/home/nextapp',
instances: 1,
autorestart: true,
watch: false,
max_memory_restart: '1G',
env: {
NODE_ENV: 'production',
PORT: 3000,
GITHUB_ID: "196807*****************",
GITHUB_SECRET: "***********************",
NEXT_PUBLIC_URL: "https://yourdomain.com",
NEXTAUTH_URL: "https://yourdomain.com",
NEXTAUTH_SECRET: "sdf",
MONGO_URI: "mongodb://localhost:27017/nextapp",
},
env_production: {
NODE_ENV: 'production'
}
}
]
};
Step 5: Starting PM2
Start your Next.js app using PM2 by running the following command in your project directory:
pm2 start ecosystem.config.js
[Optional] Using Certbot for HTTPS - Recommended
Securing your Next.js application with HTTPS is crucial for protecting sensitive data and ensuring user trust. Certbot is a widely used tool for obtaining and managing SSL/TLS certificates from the Let's Encrypt Certificate Authority. Follow these steps to set up HTTPS for your Next.js app using Certbot:
Step 1: Install Certbot
sudo apt update
sudo apt install python3-certbot-nginx
Step 2: Obtain SSL Certificate
sudo certbot --nginx -d yourdomain.com
Follow the prompts to provide an email address for renewal reminders and agree to the terms of service. Certbot will handle the certificate issuance and configuration for NGINX.
Advertisement
Step 3: Verify HTTPS Configuration
sudo nginx -t
If the test is successful, reload NGINX to apply the changes:
sudo systemctl reload nginx
Step 4: Automate Certificate Renewal
sudo systemctl enable certbot.timer
This command ensures that Certbot will renew your certificates automatically when they are about to expire.
Step 5: Verify Renewal
sudo certbot renew --dry-run
If the dry run completes without errors, you're all set. Certbot will handle certificate renewal automatically when necessary.
Advertisement
Step 6: Test HTTPS Connection
Finally, test your Next.js application over HTTPS to ensure that everything is working correctly. You can do this by navigating to your domain in a web browser and verifying that the connection is secure.
Step 7: Redirect HTTP to HTTPS (Optional)
To ensure that all traffic to your site is secure, you can set up a redirect from HTTP to HTTPS. Open your NGINX configuration file and add the following lines inside the server block:
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
return 301 https://$host$request_uri;
}
This configuration will redirect all HTTP traffic to HTTPS. After making changes to the NGINX configuration, test the configuration again:
Advertisement
sudo nginx -t
Then reload NGINX:
sudo systemctl reload nginx
Step 8: Pointing Your Domain to the VPS
To make your Next.js app accessible via a custom domain like yourdomain.com
, you'll need to configure your domain's DNS settings to point to your server's public IP.
🔧 Find Your VPS Public IP
Run the following command on your VPS to find its public IP address:
Advertisement
curl ifconfig.me
Take note of this IP — you’ll need it in the next step.
🌐 Update DNS Records
-
Go to your domain registrar’s dashboard (e.g., Namecheap, GoDaddy, Cloudflare).
Find the DNS settings or DNS management section.
Advertisement
Add an A record pointing your domain to your VPS IP:
- Host:
@
- Type:
A
- Value:
<your VPS IP>
- TTL: Automatic or 3600 seconds
Optional: Add a www
record to redirect www.yourdomain.com
to your root domain.
Type | Name | Value | TTL |
---|---|---|---|
A | @ | YOUR.VPS.IP | Auto |
A | www | YOUR.VPS.IP | Auto |
⚠️ DNS changes can take up to 24 hours to propagate, but they often update within a few minutes.
Advertisement
🧪 Verify DNS Resolution
Use this command to check if your domain points to your VPS:
ping yourdomain.com
💡 Pro Tip: Use a service like https://whatsmydns.net to check if your DNS records have propagated globally.
If it returns your VPS IP, DNS is configured correctly.
Advertisement
Conclusion
Your Next.js app is now ready and running in production! NGINX is serving as a reverse proxy, forwarding requests to your Next.js server, and PM2 is ensuring your app stays up and running.
By following these steps and configurations, you can successfully deploy and host your Next.js application in a production environment. Happy coding!
Advertisement