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

```bash
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](https://pm2.keymetrics.io/).

```bash
sudo npm install -g pm2
```

<mark>“-g” to install pm2 globally&nbsp;</mark> 

### **Step 3 - Build and Start your Next js Application**

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

Run Build Command

```bash
npm run build
```

```bash
pm2 start npm --name "my-next-app" -- start
```

### **Step 4 - Open Port & Setup**

```bash
firewall-cmd --zone=public --add-port=3000/tcp --permanent
```

```bash
firewall-cmd --reload
```

```bash
/usr/sbin/setsebool httpd_can_network_connect true
//OR
/usr/sbin/setsebool httpd_can_network_connect 1
```

<mark>To make the changes persist. Use “-P”</mark>

```bash
/usr/sbin/setsebool -P httpd_can_network_connect 1
```

Now Restart your Apache server

```bash
service httpd restart
```

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

**Port 80 :**

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

    <Proxy *>
        Require all granted
    </Proxy>

    ProxyPass / http://127.0.0.1:3000/
    ProxyPassReverse / http://127.0.0.1:3000/
    ...
</VirtualHost>
```

**Port 443 :**

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

Restart your Apache server

```bash
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
    

```bash
pm2 show my-next-app

//OR

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
    

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