
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.
First, let's ensure our server has the required packages installed. Open a terminal and run the following commands:
apt updateapt install nginx -yThis command installs the Nginx web server.
curl -fsSL https://deb.nodesource.com/setup_21.x | sudo -E bash -sudo apt-get install -y nodejsnpm install -g pm2Now, let's prepare our Next.js app. Navigate to your project directory and execute the following commands:
npm installnpm run buildnpm run startCreate 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:
Create an ecosystem configuration file for PM2. Open a text editor and paste the following configuration:
pm2 start ecosystem.config.jsSecuring your Next.js application with HTTPS is crucial for protecting sensitive data and ensuring user trust.
sudo apt updatesudo apt install python3-certbot-nginxsudo certbot --nginx -d yourdomain.comsudo nginx -tIf successful, reload NGINX:
sudo systemctl reload nginxsudo systemctl enable certbot.timersudo certbot renew --dry-runYour Next.js app is now ready and running in production with NGINX as a reverse proxy and PM2 keeping it alive.