Posted by Kosal
In the ever-evolving landscape of web development, Next.js stands out as a powerful React-based framework that simplifies the creation of fast and scalable web applications. Combining it with PM2, a production process manager, streamlines the deployment and management process, ensuring your Next.js applications run smoothly on Ubuntu servers.
sudo apt update
sudo apt install nginx
sudo systemctl start nginx
sudo systemctl enable nginx
sudo apt-get update && sudo apt-get install -y ca-certificates curl gnupg
curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | sudo gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg
NODE_MAJOR=20
echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_$NODE_MAJOR.x nodistro main" | sudo tee /etc/apt/sources.list.d/nodesource.list
sudo apt-get update && sudo apt-get install nodejs -y
For details on Node.js installation, please visit the Installing Node.js 20 on Ubuntu: Step-by-Step Guide for a step-by-step guide.
sudo npm install pm2@latest -g
git clone https://github.com/your-username/your-nextjs-project.git
Replace the URL with your Next.js project's GitHub repository URL.
cd your-nextjs-project
npm install
npm run build
pm2 start npm --name "nextjs-app" -- start
Replace "nextjs-app"
with your desired PM2 process name.
pm2 save
pm2 startup
Follow the instructions provided by pm2 startup
to set PM2 to start on boot.
sudo nano /etc/nginx/sites-available/your-domain
Configure Nginx (Example Configuration):
Paste the Nginx configuration:
server {
listen 80;
server_name your-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;
}
}
Replace your-domain.com
with your actual domain or server IP address.
sudo ln -s /etc/nginx/sites-available/nextjs-app /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
Access your server's IP address or domain in a web browser. It should display your Next.js application served through Nginx.