Setting Up reverse Proxy for Next JS application in Ubuntu 22.04
We will see how we can Serve the Next Application to Apache2 Port 80
Steps
Install Nodejs 16
Create a next Application
install pm2 and Start the Next Application with pm2
Install Apache2, Disable the default Site,
Create a new site, configuration and enable it
Allow proxy in Appahe2
Testing
Install Nodejs 16
we will install the node js 16 version for creating our Next application (Most of the time it requires installing a specific version instead of the latest one)
curl -sL https://deb.nodesource.com/setup_16.x -o /tmp/nodesource_setup.sh
sudo bash /tmp/nodesource_setup.sh
sudo apt-get install -y nodejs
node -v
Create a next Application
npx create-next-app nextapp
# change dir to nextapp
cd nextapp
Install pm2 and Start the Next Application with pm2
we will start our application from PM2 instead of npm run dev
because we want our application to run even if we close the terminal as the Process and also restart the Nextjs Application on reboot.
# Instaling pm2
npm i -g pm2
Building Next Js
Before starting the Application we need to build the application
Starting Next Js with PM2
pm2 start npm --name 'my-app-with-pm2' -- run start
#verify
pm2 status
Serving Next Js from Apache2 with Proxy
Install Apache2, Disable the default Site
sudo apt install -y apache2
verify its service running successfully
sudo systemctl status apache2
Disable apache2 its default site
sudo a2dissite 000-default.conf
Create a new site, set the configuration, and enable it
we will create a new apache2 conf file inside /etc/apache2/sites-available/ nextapp.conf
and add the below configuration by replacing ith ServerName
with your server IP address and serverAdmin
email
sudo vim /etc/apache2/sites-available/nextapp.conf
Please replace and serverAdmin
, ServerName
with your server IP address or your domain name if you want to serve this application with your domain name, you also need to Point this Public server IP address to your domain registrar.
<VirtualHost *:80>
ServerName 192.168.1.113
ServerAdmin usama@devops.com
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
ProxyPass / http://127.0.0.1:3000/
ProxyPassReverse / http://127.0.0.1:3000/
ProxyRequests Off
</VirtualHost>
#Enable our brand new next application site
sudo a2ensite nextapp.conf
Allow proxy in Appahe2
sudo a2enmod proxy && sudo a2enmod proxy_http
# Restar Apache2
sudo systemctl restart apache2
Verify
go to your browser and enter your Server IP address or domain name if you have pointed to this server , in my case 192.168.1.113
Note: The application will still be available on Port 3000 from the server IP address and in the Amazon EC2 server we explicitly have to allow from security groups,