Skip to content

Instantly share code, notes, and snippets.

@SumitKumar-17
Created March 21, 2025 05:05
Deploying a Next.js/React.js/ Express.js Server/Vite Project Application with Nginx and PM2

Deploying a Next.js/React.js/ Express.js Server/Vite Project Application with Nginx and PM2

  • This script is written for an Ubuntu EC2

1. System Update and Nginx Installation

sudo apt-get update
sudo apt-get upgrade
sudo apt-get install nginx

2. Install Node.js via NVM

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash
source ~/.bashrc
nvm install 20.15.1
nvm use 20.15.1

3. Generate SSH Key

ssh-keygen -t rsa -b 4096 -C "email id" -f ~/.ssh/id_rsa -N ""
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_rsa
cat ~/.ssh/id_rsa.pub

Add this ssh-key in your github.

4. Clone and Setup Project

git clone <repo-url> ~
cd project
npm i
npm run build
cd ~

5. Configure Nginx for Reverse Proxy

sudo nano /etc/nginx/sites-available/{folder_name}

Add the following content:

server {
    listen 80;
    server_name domain_name publicIpv4_address(of EC2);

    location / {
        proxy_pass http://127.0.0.1:3000;
        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;
    }
}

Enable the configuration and restart Nginx:

sudo ln -s /etc/nginx/sites-available/{folder_name} /etc/nginx/sites-enabled
sudo nginx -t
sudo service nginx restart

NOte: keep any folder name ,it will be needede when you reload the server.

6. Process Management with PM2

npm i -g pm2
pm2 start npm --name "Backend hosting" -- start

Note: before doing this add the Ipv4 address in AWS Route53 or the DNS Servers else it will fail

7. Setup HTTPS with Certbot

sudo apt update
sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d domain_name

PM2 Commands for Different Frameworks

Framework PM2 Command
Vite Project pm2 start npm --name "vite-preview" -- run preview
Next.js Server pm2 start npm --name "Backend hosting" -- start
React App pm2 start "serve -s build -l 3000" --name react-app
Express.js Server pm2 start server.js

Nginx Configuration for PHP Hosting

If hosting a PHP-based project instead of Next.js/React/Vite:

server {
    listen 80;
    server_name your-domain-name-or-public-ip;

    root /var/www/html;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

Useful References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment