Setting Up reverse Proxy for Next JS application in Ubuntu 22.04

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

  1. Install Nodejs 16

  2. Create a next Application

  3. install pm2 and Start the Next Application with pm2

  4. Install Apache2, Disable the default Site,

  5. Create a new site, configuration and enable it

  6. Allow proxy in Appahe2

  7. 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

# Instaling pm2
npm i -g pm2
pm2 start npm --name 'my-app-with-pm2' --  run dev
#verify
pm2 status

Install Apache2, Disable the default Site

sudo apt install -y apache2

verify its service running successfully

sudo systemctl status apache2

# Disable its default site
sudo a2dissite 000-default.conf

Create a new site, configuration and enable it

create a new 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
<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 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, but we can add an additional layer of security by enabling ufw and only allowing SSH and HTP requests.