How to Deploy Next.js in Nginx with PM2 on Ubuntu Server
How to Deploy Next.js in Nginx with PM2 on Ubuntu Server
This step-by-step tutorial will show you how to install Next.js in Nginx on an Ubuntu server using PM2. You can easily deploy your Next.js application to a production server using the instructions in this article. We'll walk you through each step, starting with using SSH to get into your Ubuntu server, installing Node.js and NPM, configuring Nginx and PM2, and then deploying your Next.js application. Regardless of the amount of experience with server administration or development, our guide will provide you all the information you need to rapidly and successfully deploy your Next.js application. Let's get started!
# 1
Basic Instance Setup Command
sudo apt-get update
sudo apt-get upgrade
# 2
Install Npm
sudo apt install npm
# 3
Need to create Next Js app
npx create-next-app@latest
# or
yarn create next-app
# 4
What is PM2?
PM2 refers to a process manager called "Process Manager 2." PM2 is a popular tool used for managing Node.js applications in production environments
Install PM2
npm install -g pm2
Move /var/www/
cd /var/www/
Setup NVM .Run Below Command
Check update version
https://github.com/nvm-sh/nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash
exec #SHELL
# 5
Create Next js Application
npx create-next-app frontend
# 6
Setup Nginx
sudo apt-get nginx
# 7
Enable UFW
sudo ufw allow "Nginx Full"
# 8
Move current directory to nginx site-available folder with Command
cd /etc/nginx/site-available/
# 9
Create new file
touch frontend
# open frontend file using nano or vim
nano frontend
# 10
server {
listen 80;
listen [::]:80;
server_name default;
location / {
# reverse proxy for next server
proxy_pass http://0.0.0.0: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;
}
}
# 11
Remove default nginx file
rm default
cd ..
cd site-enabled
rm default
# copy of site-available/frontend file paste into site-enabled section
sudo ln -s /etc/nginx/sites-available/frontend /etc/nginx/sites-enabled
# 12
Nginx test
sudo nginx -t
# 13
Restart nginx
sudo systemctl restart nginx
# 14
cd /var/www/
mkdir frontend
cd frontend
# next js run as a backend
pm2 start npm --name frontend -- start
Thank you for reach out my blog.If you any queries just contact me via contact form or other social handle
Peace!!!