Deploy Node with Nginx on Ubuntu 22.04

Today I'm gonna share how to Install and Configure NodeJS with Nginx and I am using AWS EC2 (t3.micro) for writing this tutorial.

Step 1 — Creating an EC2 Instance, DNS and SSH

First, we require an ec2 instance so launch an instance with your preferred size, you can also attach an Elastic IP to your instance.

In your DNS Server (Route 53 or Cloudflare) add these records.

Record NameRecord TypeValue
@A[Server_IP]
wwwCNAMEexample.com

Now, we have pointed from our DNS to our new server IP, now we need to log in into our new server using SSH client.

Example: ssh -i "YourKey.pem" ubuntu@SERVER_IP

Step 2 — Setup and Installing Requirements

Set a Timezone on Ubuntu:

sudo timedatectl
sudo timedatectl set-timezone Asia/Kolkata

If first time using apt in this session, run the update command to update the package manager cache:

sudo apt update -y

Install Node JS:

cd ~
curl -sL https://deb.nodesource.com/setup_18.x -o nodesource_setup.sh
sudo bash nodesource_setup.sh
sudo apt install nodejs
sudo apt-get install nsolid -y
node -v

Install Nginx:

sudo apt install nginx

After installing, you can request to your domain (example.com), You will get nginx default page as response.

**Step 3 — Creating a Database **

If you are using any third party database like RDS then you can skip this step.

Create a MySQL database for Laravel application; so execute the following command on command line to create database for Laravel app:

sudo apt install mysql-server
sudo mysql_secure_installation
sudo mysql
CREATE DATABASE app_database;
CREATE USER 'app_user'@'%' IDENTIFIED WITH mysql_native_password BY 'password';
GRANT ALL ON app_database.* TO 'app_user'@'%';

SHOW DATABASES;
exit;

Step 4 — Install and Configure NodeJS Project in Ubuntu 22.04

You can set up the git into your server following this Link

Clone your project from git

cd /home/ubuntu/
git clone _REPO_

Install dependencies

cd PROJECT_NAME
npm i
sudo npm install -g nodemon
sudo npm install -g pm2

pm2 status

Start the app

pm2 start app.js  --node-args="--max-old-space-size=8192"

Pm2 Auto Startup

sudo su -c "env PATH=$PATH:/usr/bin pm2 startup systemd -u ubuntu --hp /home/ubuntu"

Step 4 — Setup Nginx

sudo nano /etc/nginx/sites-available/project_name

Change the port as your project proxy_pass http://localhost:5000; and server_name Copy, and paste the following Nginx Configuration

server {
    listen [::]:80;
    listen 80;
    server_name example.com *.example.com;

    location / {
        proxy_pass http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

Copy the config to sites-enabled.

sudo ln -s /etc/nginx/sites-available/project_name /etc/nginx/sites-enabled/

sudo nginx -t
sudo systemctl reload nginx
sudo systemctl status nginx

Now you can request domain http://example.com and your site should be visible.

Step 5 — Installing SSL

sudo apt install certbot python3-certbot-nginx

sudo certbot --nginx -d example.com -d www.example.com

sudo systemctl status certbot.timer
sudo certbot renew --dry-run

Now you can request the website using https://example.com.

Creating Shell Script (Quick Actions) [OPTIONAL]

For restarting the Nginx and pulling Code from Git, I have created a shell script.

sudo nano /usr/local/bin/z

For creating the shell script, modify copy, and paste the following code to your terminal.

#!/bin/bash
select opt in Sync Restart ChangeDir CheckStatus Quit
do
        case $opt in
        Sync)  
                git pull origin master
                echo "Code synced"
                exit 0
                ;;
    Restart)  
                pm2 stop /home/ubuntu/PROJECT_NAME/app.js && pm2 start /home/ubuntu/PROJECT_NAME/app.js  --node-args="--max-old-space-size=8192"
                sudo nginx -t && sudo systemctl restart nginx
                echo "Nginx has been restarted."
                exit 0
                ;;
        ChangeDir)
                cd /home/ubuntu/PROJECT_NAME/
                echo -e '\nHit [Ctrl]+[D] to exit this child shell.'
                $SHELL
                exit 0
                ;;
        CheckStatus)  
                sudo systemctl status nginx
                echo "Shell by Sanjay"
                exit 0
                ;;
        Quit)
                echo "Exited!"
                exit 0
                ;;
        *)
                echo "invalid option"
                ;;
        esac
done
sudo chmod +x /usr/local/bin/z

Now press the z key and hit enter.

ubuntu@ip-172-31-0-94:~$ z
1) Sync
2) Restart
3) ChangeDir
4) CheckStatus
5) Quit
#?

Select any option by pressing the number keys.

Hope you guys like the article. If you encounter any difficulties in understanding this approach, please don't hesitate to leave a comment.

Troubleshoot

Stop all processes Akl > pm2 stop all

if you are using foreverforever start -a -l /dev/null app.js and forever restartall to delete logs find /home/ubuntu/.forever -name "*.log" -type f -delete