How to Deploy a Production Environment for Node.js on an Ubuntu Cloud Server?

05-02-2024 02:06:58

For Node.js applications, a secure, fast, and robust production environment is crucial for user experience. This guide, based on an Ubuntu 20.04 cloud server, introduces methods for deploying a Node.js production environment, serving as a reference for Node.js system administrators.

Setting Up the Firewall

Firewalls ensure that only specified ports can receive or send data, reducing the risk of server attacks.

Install the firewall.

$ sudo apt-get install ufw

Allow the necessary ports.

$ sudo ufw allow 80
$ sudo ufw allow 443
$ sudo ufw allow 22

Enable the firewall and check its status.

$ sudo ufw enable
$ sudo ufw status

Creating the Application

The application uses the Express.js framework, with the Helmet.js component for enhanced security. Install the Helmet.js component.

$ npm i --save helmet

The Node.js application code is as follows, with the filename server_file.js.

const express = require("express");
const helmet = require("helmet");
const app = express();
app.use(helmet());
app.listen(8080);

Next, install PM2 to run the Node.js application as a background process. PM2 can restart the application in case of an accidental shutdown, while also managing application logs and monitoring performance.

$ sudo npm install pm2 -g
$ pm2 start server_file.js
$ pm2 startup

Configuring Nginx

Nginx is a widely used web server in production environments, known for its ease of deployment, fast operation, and robust stability. It manages all HTTP requests, integrating SSL, caching, and reverse proxy, allowing the Node.js application to scale freely.

Install Nginx.

$ sudo apt-get install nginx

Verify Nginx is running.

$ sudo systemctl status nginx
Active: active (running)

Edit the Nginx configuration file to redirect HTTP requests to HTTPS. Replace example.com with the actual domain name.

# redirect HTTP traffic to HTTPS
server {
        listen 80;
        server_name example.com www.example.com;
        return 301 https://example.com$request_uri;
}

# HTTPS server
server {
        listen 443 ssl;
        server_name example.com;
        access_log /var/log/nginx/example.com.log;
        ssl_certificate /path/to/certificate/example.com.crt;
        ssl_certificate_key /path/to/key/example.com.key;
        location / {
            proxy_set_header HOST $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_pass http://127.0.0.1:8080; # Node.js Application
        }
}

Restart Nginx to apply changes.

$ sudo systemctl restart nginx

Finally, access the application via https://example.com in a browser. If it loads successfully, the Node.js application has been successfully deployed.