How to deploy Next js application on any Linux server

How to deploy Next js application on any Linux server

Prerequisite :

  • Linux Server, I'm using AWS Lightsail Linux (centos 8) server

  • Next js application in the GitHub repo.

  • Node & Apache pre-install and setup

I'm assuming you've previously met all of the prerequisites.

Step 1 - Clone your repo in your domain root directory

NOTE: You can configure your domain and its root directory how you want.

git clone my-next-app:username/my-next-app.git

Step 2 - Install PM2

if you are wondering what is PM2, it is a production process manager for Node.js applications with a built-in load balancer.

for more information, you can check out their site here.

sudo npm install -g pm2

“-g” to install pm2 globally 

Step 3 - Build and Start your Next js Application

cd into your project directory e.g “/my-next-app”

Run Build Command

npm run build
pm2 start npm --name "my-next-app" -- start

Step 4 - Open Port & Setup

firewall-cmd --zone=public --add-port=3000/tcp --permanent
firewall-cmd --reload
/usr/sbin/setsebool httpd_can_network_connect true
/usr/sbin/setsebool httpd_can_network_connect 1

To make the changes persist. Use “-P”

/usr/sbin/setsebool -P httpd_can_network_connect 1

Now Restart your Apache server

service httpd restart

Step 5 - Make a few changes to the “your-domain.conf” file

Port 80 :

<VirtualHost *:80>
    ProxyRequests Off
    ProxyPreserveHost On
    ProxyVia Full

    <Proxy *>
        Require all granted

    ProxyPass /
    ProxyPassReverse /

Port 443 :

<VirtualHost *:443>
    ProxyPreserveHost on
    ProxyPass / http://localhost:3000/
    ProxyPassReverse / http://localhost:3000/
    LogLevel warn

Restart your Apache server

service httpd restart

YAY ! 🥳 Visit your site and access your Next js application

⚙ Troubleshooting

If you get an error, make sure you follow each step exactly. Moreover, if you continue to encounter problems, consider the solutions listed below.

Site Throwing 503

  • Make sure there is no error occurring on build and run time

  • Check if the application is running

pm2 show my-next-app


pm2 monit
  • The port on which your application is running is open and accessible, in my case it was 3000 (checkout Step 4)

  • Run the following command to check open and running ports

netstat -tulpn | grep LISTEN
  • Restart your instance manually, Go to your server management panel and restart your server, and re-run Step 3 and Step 4

In the end, if the given solution doesn't work for you then like a PRO Google 😎 it.