Setting Up a Node.js Application with Nginx and SSL

basanta sapkota

In this guide, we will walk you through the entire process of setting up a Node.js application, configuring Nginx as a reverse proxy, and securing your application with SSL using Let's Encrypt. This setup can be applied to any machine and domain, making it a versatile solution for deploying Node.js applications.

Prerequisites

Before we begin, ensure you have the following:

  1. A server running a Linux distribution (e.g., Ubuntu, CentOS, Rocky Linux).
  2. A registered domain name pointing to your server's IP address.
  3. Node.js and npm installed on your server. You can install them using your package manager or from the official Node.js website.
  4. Nginx installed on your server. You can typically install it using:

    • For Ubuntu/Debian:
      sudo apt update
      sudo apt install nginx
      
    • For CentOS/Rocky Linux:
      sudo yum install epel-release
      sudo yum install nginx
      
  5. Basic knowledge of terminal commands and server management.

Step 1: Setting Up Your Node.js Application

1. Create Your Node.js Application

First, create a directory for your Node.js application:

mkdir ~/my-node-app
cd ~/my-node-app

Next, initialize a new Node.js project:

npm init -y

This command creates a package.json file with default values. Now, create an index.js file as the main entry point for your application:

touch index.js

Open index.js in your preferred text editor and add the following code:

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello Node!\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

2. Start Your Node.js Application

You can start your application using Node.js:

node index.js

To keep your application running in the background and ensure it restarts on crashes or server reboots, use PM2:

npm install -g pm2
pm2 start index.js --name my-node-app
pm2 startup
pm2 save

This command will start your application and set it to launch on system startup.

Step 2: Installing and Configuring Nginx

1. Configure Nginx as a Reverse Proxy

Nginx will act as a reverse proxy to forward requests from port 80 (HTTP) and port 443 (HTTPS) to your Node.js application running on port 3000.

Create a new Nginx configuration file:

sudo nano /etc/nginx/conf.d/my-node-app.conf

Add the following configuration, replacing node.npch.website with your actual domain name:

server {
    listen 80;
    server_name node.npch.website;

    location / {
        proxy_pass http://localhost:3000;  # Node.js app port
        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;
    }
}

2. Test the Nginx Configuration

Before reloading Nginx, it's crucial to test the configuration for any syntax errors:

sudo nginx -t

If everything is fine, reload Nginx:

sudo systemctl reload nginx

Step 3: Securing Your Application with SSL

1. Install Certbot

Certbot is a tool to obtain SSL certificates from Let's Encrypt. Install Certbot and the Nginx plugin:

  • For Ubuntu/Debian:

    sudo apt install certbot python3-certbot-nginx
    
  • For CentOS/Rocky Linux:

    sudo yum install certbot python3-certbot-nginx
    

2. Obtain an SSL Certificate

Run the following command to automatically obtain and configure SSL certificates for your domain:

sudo certbot --nginx -d node.npch.website

Follow the prompts to enter your email address and agree to the terms of service. Certbot will automatically update your Nginx configuration to redirect HTTP traffic to HTTPS.

3. Verify SSL Installation

Once the installation is complete, you can verify that your SSL certificate is working by visiting your domain in a web browser using https://node.npch.website.

4. Set Up Automatic Renewal

Let's Encrypt certificates are valid for 90 days. To automatically renew the certificates, add a cron job:

sudo crontab -e

Add the following line to run the renewal process daily:

0 0 * * * certbot renew --quiet

This cron job checks for certificate renewal every day at midnight.

Step 4: Finalizing and Testing Your Setup

1. Check Nginx Status

Ensure that Nginx is running without errors:

sudo systemctl status nginx

2. Test the Node.js Application Through Nginx

Now, open a web browser and navigate to http://node.npch.website and https://node.npch.website. You should see "Hello Node!" displayed in your browser.

3. Check for Firewall Rules

Make sure your firewall allows traffic on ports 80 and 443. For example, on CentOS/Rocky Linux, you can check the firewall status:

sudo firewall-cmd --list-all

If ports 80 and 443 are not open, you can open them with:

sudo firewall-cmd --add-service=http --permanent
sudo firewall-cmd --add-service=https --permanent
sudo firewall-cmd --reload

Conclusion

Congratulations! You have successfully set up a Node.js application with Nginx as a reverse proxy and secured it with SSL using Let's Encrypt. This setup is scalable and suitable for any production environment. Remember to monitor your application and server for performance and security.

Post a Comment