Comprehensive Guide to Deploying Node.js, Next.js, and React.js with Nginx Reverse Proxy Using PM2

Comprehensive Guide to Deploying Node.js, Next.js, and React.js with Nginx Reverse Proxy Using PM2

Embark on a seamless deployment journey for your Node.js, Next.js, and React.js applications. Our guide simplifies the process using Nginx as a reverse proxy and PM2 for efficient process management. Plus, we'll elevate your application's security by incorporating SSL for a worry-free online experience.

Effortlessly deploy your Node.js, Next.js, and React.js projects with our step-by-step tutorial. Utilize Nginx as a reliable reverse proxy, leverage PM2 for streamlined process management, and enhance security with the addition of SSL. Simplify your deployment strategy and fortify your online presence effortlessly.

Getting Started

Prerequisites

  • Next.js, Node.js, React.js Application.
  • A Domain Name for DNS Configuration

Step-1 Create a Virtual Machine Instance

Create a Virtual Machine instance by following these steps, whether on Digital Ocean, Vultr, Azure, or AWS:

  • Click on "Create Virtual Machine."
  • Choose a base image, such as Debian or another Linux-based image.
  • Select the desired RAM, CPU, and disk size for optimal performance.
  • Add a secure password for SSH connection.
  • Finally, create the Virtual Machine with the specified configuration.

Step 2: SSH Connection and Basic Setup

To initiate an SSH connection to the virtual machine (VM), use the following command:

ssh username@ip_address

Next, install Node.js on the Linux-based VM by following these steps:

curl https://raw.githubusercontent.com/creationix/nvm/master/install.sh | bash   # Download the installer script from GitHub.

source ~/.profile  # Reload the environment variables into your current session.

nvm ls-remote  # List the available versions of Node.js.

nvm install 20.9.0  # Command to download and install a specific Node.js version.

Additionally, install Uncomplicated Firewall (UFW), a simplified firewall management interface that allows you to control which applications or ports have outside connections:

sudo apt install ufw
  • Note: It is always a good practice to create a new user instead of working with the root user. Also, set up passwordless login with the help of public keys for enhanced security.

Setting Up Web App

We are utilizing GitHub for version control. Begin by installing Git:

sudo apt install git  # Install Git
git clone your_repo

Next, install the npm modules:

npm install

For Next.js and React.js, proceed to build your code for production:

npm run build

Test the Node.js, React.js, or Next.js application to ensure it is working successfully:

npm start  # This command may vary, e.g., 'node app.js'
  • Additionally, consider the use of GitHub Actions for automatic deployment, a topic we will explore in the next steps.

Setting Up PM2 Process Manager

While running npm start keeps the application running, it has downsides such as not automatically restarting on stop or reboot, and it can be challenging to manage multiple applications. PM2 is an advanced process manager for production Node.js applications, providing features like a load balancer, log facility, startup script, and microservice management.

To install PM2 globally on your droplet, execute the following command:

npm install -g pm2

Navigate to the application directory (if not already there):

cd /home/usr/app

Start the application using PM2:

pm2 start npm --name "app" -- start

PM2 will automatically restart the application if it crashes or if the server reboots. To ensure PM2 starts on boot, run:

pm2 startup

This command generates a script that you can copy and paste into your terminal to enable PM2 to start on boot. Save the current PM2 processes:

pm2 save

Use the following commands to update the running application and manage it with PM2:

pm2 list  # Gives a list of all running applications.
pm2 restart app  # Restarts the given app.
pm2 stop app  # Stops the given app.

Now that our application is running in the background using PM2 on a given port (e.g., 3000), it's time to set up Nginx.

Setting Up Nginx

Install Nginx for the Server

Nginx serves as a versatile web server and can be employed as a reverse proxy, load balancer, mail proxy, and HTTP cache. To install Nginx, use the following command:

sudo apt install nginx

Grant Nginx full access to the outside world, as it will be communicating with users:

sudo ufw allow 'Nginx HTTP'
sudo ufw status  # List of applications with access

Checking Your Web Server

After the installation process, Nginx is started automatically. To verify that the web server is up and running, use the following command:

systemctl status nginx

Configuring Nginx for Web App

Nginx will handle the routing for our Next.js, React.js, and Node.js application. Let's create a new Nginx configuration file for the application:

sudo vi /etc/nginx/sites-available/app

Press i to enter insert mode in vi. Paste the following configuration, replacing server_name with your domain name or VM IP address:

server {
  listen 80;
  server_name YOUR_IP_ADDRESS_OR_DOMAIN_NAME;
  location / {
    proxy_pass http://localhost: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;
  }
}

Save and close the file by typing Esc, then :wq in vi.

  • Note that proxy_pass is set to the port where our application is running through PM2, and server_name can be an IP address or domain name (e.g., unizoy.com).

Create a symbolic link to enable the configuration, creating a shortcut from the sites-available folder to the sites-enabled folder:

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

Test the Nginx configuration for any syntax errors:

sudo nginx -t

If the configuration test is successful, restart Nginx:

sudo service nginx restart

Setting Up DNS in Domain.

If your server is identified by a domain name, you must configure the DNS settings for that domain.

Visit the dashboard of your domain provider and navigate to the DNS settings for the domain. Target the domain to the IP address of your VM. Click on "Add New Record" and provide the following details:

Type    Name    Value           TTL
A       @       VM_IP_Addrs     30min
  • Note: If your server contains subdomains, such as backend.unizoy.com, use the subdomain name (e.g., "backend") instead of "@".

After the DNS update has been applied, visiting the domain name should display the PM2 web application.

Setting Up Free SSL

SSL certificates enable websites to use HTTPS, providing a more secure connection than HTTP. These certificates are data files hosted on a website's origin server and enable SSL/TLS encryption.

Step 1: Install Snapd

Install Snapd by following the official instructions.

sudo apt install snapd

Step 2: Install Certbot

Install Certbot using Snap.

sudo snap install --classic certbot

Step 3: Prepare Certbot Command

Create a symbolic link to ensure the certbot command can be run.

sudo ln -s /snap/bin/certbot /usr/bin/certbot

Step 4: Get SSL Certificate

Run the following command to get a certificate and have Certbot automatically edit your Nginx configuration to enable HTTPS access.

sudo certbot --nginx

Step 5: Confirm Certbot Worked

Visit the HTTPS version of your website (e.g., https://unizoy.com) to confirm that Certbot worked.

Congratulations! You have successfully deployed your web application with SSL. For future deployments, consider using Docker for a fast and easy setup.

If you encounter any issues or have questions, feel free to reach out to me on LinkedIn - Rajpurohit Vijesh. I am always available to help the community.

Also, if you need an expert problem solver, check out Unizoy. Our team specializes in SaaS products, AI, web, and app development, ensuring transparency and client satisfaction at every step of the product development process.