Compute Engine Google Cloud

Install Node.js and NPM with Nginx on Ubuntu 20.04 – Google Cloud

Install Node.js and NPM on Ubuntu 20.04. Node.js is a JavaScript platform for programming that allows users to build network applications quickly.

In this guide, you will learn how to setup a production Node.js environment on Google Cloud with Ubuntu 20.04 LTS, Nginx and HTTPS.

Choose Best Hosting for your Business

PlatformReviewsPricing
Siteground★★★★★$3.95
Kinsta – Google Cloud★★★★★$30

Prerequisites

  1. Your Compute Engine Instance running, see the Setting up Compute Engine Instance.
  2. Domain name is pointed to your virtual machine.
  3. For setting up Cloud DNS, see the Setting up Google Cloud DNS for your domain.

Initial Setup

Start by updating the packages to the latest version available.

sudo apt update
sudo apt upgrade

Install Node.js from Default Repository

The default Ubuntu repositories have the package of Node.js 10. You can install is directly using the apt install command.

sudo apt install nodejs

Once the installation is completed you check the version using the following command.

nodejs --version 

Install Specific Node.js version

You can install specific Node.js version from the Node.js repositories.

At this time the latest stable version available is v14.x.

You can install it using the following command.

curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt install -y nodejs

Once the installation is complete you can check the node.js version and npm version using the following commands

node -v
npm -v

Some packages requires compiling from source so you need to install the build-essential package.

sudo apt install build-essential

Create a Node.js Application

Now you can create a demo Node.js app

cd ~/
sudo nano server.js

Insert the following code into the file

const http = require('http');
const hostname = 'localhost';
const port = 3000;

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

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

Save the file and exit.

Install Process Manager

sudo npm install [email protected] -g

Now you can start your app using the process manager

pm2 start server.js

Now your Node.js application is running in the background

Install and Set up Nginx

sudo apt install nginx

Remove default configurations

sudo rm /etc/nginx/sites-available/default
sudo rm /etc/nginx/sites-enabled/default

Create new Nginx configuration

sudo nano /etc/nginx/sites-available/yourdomainname.com

Paste the following

server {
listen [::]:80;
listen 80;

server_name yourdomainname.com www.yourdomainname.com;

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 exit the file

Enable your configuration by creating a symbolic link

sudo ln -s /etc/nginx/sites-available/yourdomainname.com /etc/nginx/sites-enabled/yourdomainname.com

Check your Nginx configuration and restart Nginx

sudo nginx -t
sudo service nginx restart

Now you can visit your domain name in browser, you should view the output of your server.js (Welcome to Node.js!)

Create SSL certificate and enable HTTP/2

HTTPS
HTTPS is a protocol for secure communication between a server (instance) and a client (web browser). Due to the introduction of Let’s Encrypt, which provides free SSL certificates, HTTPS are adopted by everyone and also provides trust to your audiences.

sudo apt install python3-certbot-nginx

Now we have installed Certbot by Let’s Encrypt for Ubuntu 20.04, run this command to receive your certificates.

sudo certbot --nginx certonly

Enter your email and agree to the terms and conditions, then you will receive the list of domains you need to generate SSL certificate.

To select all domains simply hit Enter

The Certbot client will automatically generate the new certificate for your domain. Now we need to update the Nginx config.

Redirect HTTP Traffic to HTTPS with www in Nginx

Open your site’s Nginx configuration file add replace everything with the following. Replacing the file path with the one you received when obtaining the SSL certificate. The ssl_certificate directive should point to your fullchain.pem file, and the ssl_certificate_key directive should point to your privkey.pem file.

server {
      listen [::]:80;
      listen 80;
      
      server_name yourdomainname.com www.yourdomainname.com;

      return 301 https://yourdomainname.com$request_uri;
} 

server {
      listen [::]:443 ssl;
      listen 443 ssl;

      server_name www.yourdomainname.com;

      ssl_certificate /etc/letsencrypt/live/yourdomainname.com/fullchain.pem;
      ssl_certificate_key /etc/letsencrypt/live/yourdomainname.com/privkey.pem;

      return 301 https://yourdomainname.com$request_uri;
}   

server {
      listen [::]:443 ssl;
      listen 443 ssl;

      server_name yourdomainname.com;

      ssl_certificate /etc/letsencrypt/live/yourdomainname.com/fullchain.pem;
      ssl_certificate_key /etc/letsencrypt/live/yourdomainname.com/privkey.pem;

      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;
      }
} 

Now you have enabled SSL Hardening, created a Content Security Policy, X-XSS-Protection, Clickjacking, MIME Sniffing, Referrer Policy, Access Control Allow Origin.

These are some Nginx security tweaks by closing all areas of attacks.

Hit CTRL+X followed by Y to save the changes.

Check your configuration and restart Nginx for the changes to take effect.

sudo nginx -t
sudo service nginx restart

Renewing SSL Certificate

Certificates provided by Let’s Encrypt are valid for 90 days only, so you need to renew them often. Now you set up a cronjob to check for the certificate which is due to expire in next 30 days and renew it automatically.

sudo crontab -e

Add this line at the end of the file

0 0,12 * * * certbot renew >/dev/null 2>&1

Hit CTRL+X followed by Y to save the changes.

This cronjob will attempt to check for renewing the certificate twice daily.

Get your Professional Google Cloud Architect certificate with this easy to learn course now.

Conclusion

Now you have learned how to install Node.js on Ubuntu 20.04 and create an application and secure it with Let’s Encrypt SSL certificate.

Thanks for your time. If you face any problem or any feedback, please leave a comment below.

Cloudbooklet builds a large collection of Linux based guides and tutorials on Cloud platforms like Google Cloud, AWS, Azure, DigitalOcean and more

Write A Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.