How to Deploy your First Node.js Application on your Ubuntu Web Server

Last updated: July 19th 2023

Introduction

Node.js is an open source JavaScript runtime platform used to run JavaScript code on the server-side. You can write any kind of server-side script for web applications using Node.js. Node.js is supported by a variety of platforms like Windows, Linux and MacOS. In this tutorial we will show how a Node.js application can be deployed to a Webdock Ubuntu server instance.

Prerequisites

Installing Required Software

If you choose a LAMP or LEMP Webdock stack then your Webdock server already has Node, NPM, Certbot and other software installed which you will need. If you start with a clean Ubuntu installation (18.04 Bionic Beaver or newer) or your own private server other than a Webdock LAMP/LEMP stack, you can install them by using the following commands.

# sudo apt-get update

To install node.js

# sudo apt-get install nodejs

To install npm

# sudo apt-get install npm

You can verify installation of node.js and npm by checking the version

# nodejs -v
# npm -v

Copy Node.js Code to your Webdock Instance

There are two common ways to move your code to the Webdock Instance.

  • Using Github, BitBucket or Gitlab
  • Transferring Zipped code using scp command

Copying Code Using Github, BitBucket or Gitlab

Clone your node.js application from github

# git clone https://github.com/contentful/the-example-app.nodejs

Copying Code Using scp Command

You can also upload your zipped code to the Webdock instance directly by using the 'scp' command. We will use this command to copy the files to remote servers securely. First, delete node_modules directory from node.js project and compress your code.

On Linux and MacOS

Use following command to compress the project directory

# zip -r project.zip project

It will create a project.zip file.

On Windows

For Windows, right click on the project directory and hover over the ‘Send to’ option. Now click on the ‘Compressed (zipped) folder’ and it will create a zip file of the project.

Upload Project Zip File to Webdock Instance

Now move this project zip file to Webdock instance using scp command from the local system

# scp project.zip username@IP_Address:~/

Where username is the username and IP_Address is the IP Address of your Webdock instance. This will move your project zip file to your Webdock instance. SSH to your Webdock server and next unzip this project.zip file on your Webdock server:

# unzip project.zip

Generating SSL Certificates For Node.js Application

Now that your Node.js application has been uploaded to the server, you may want to serve content from it through an SSL-secured connection. You can use Certbot to generate Let’s Encrypt free SSL certificates.

Installing Certbot

If you started with a Webdock LAMP/LEMP stack, you can skip these steps as Certbot is already installed in our LAMP/LEMP stacks.

Before installing Certbot, you need to install snapd. To do this, you can simply run the following:

$ sudo apt update && sudo apt install snapd -y

Once that's done, you can go ahead and install Certbot:

$ sudo snap install --classic certbot

Generate the SSL certificates.

If you want to generate a new certificate for your own domain for use with Node.js you should perform the following steps. If you just want to use the default certificates issued by Webdock with Certbot, as you set up your server, you can simply refer to these certificate files in the next steps. (i.e. if you want to just use the default yourserver.vps.webdock.io domain)

# sudo certbot certonly --manual

After running the above command, it will ask some questions like your email address and domain name then after confirming your domain it will generate SSL certificates.

SSL certificates generated by certbot expire after 90 days and these certificates need to be renewed before they expire. SSL certificates can be updated automatically by adding a Cron job. Open crontab and type the following,

# sudo crontab -e

And add the following cronjob.

0 8 * * *        sudo certbot renew

It will run the command to renew certificates everyday at 08:00. This command will check all the certificates and try to renew the certificates which are going to expire within 30 days.

Alternatively you can renew SSL certificates any time by using following command in the terminal

# sudo certbot certonly --force-renew -d example.com

This command will renew SSL certificates for 'example.com' domain.

Loading SSL Certificates to the Server

After generating the SSL Certificate files, you can load them into your application by using ‘https’ module as shown in the following code. Replace $DOMAIN with your domain in the code below. To see what certificates have been generated on your server already, simply list the files/directories under /etc/letsencrypt/live/ with 

# sudo ls -lah /etc/letsencrypt/live/

Node.js code:

const express = require(‘express’);
const https = require(‘https’);
const fs = require(‘fs’);
const options = {
    key: fs.readFileSync(‘/etc/letsencrypt/live/$DOMAIN/privkey.pem’),
    cert: fs.readFileSync(‘/etc/letsencrypt/live/$DOMAIN/fullchain.pem’)
};
const app = express();
app.use((req, res) =>
{
    res.end(‘Hello World’);
});

https.createServer(options, app).listen(8000);

Install Required Packages and Start the Node.js Application

Now before starting your node.js application, install any required packages as defined by your application if needed. Go to your project root directory and run the following command

# npm install

This command will check the 'package.json' file in your project and install required packages. After installing required packages, you can start the application using the following command.

# node app.js

Daemonize Application using pm2

Your Node.js application is running on Webdock server but whenever you close the terminal on your instance, the application will stop. Similarly, whenever your application code is changed, those changes will not reflect to your server automatically.

To resolve this problem, we can use pm2, which is a package from npm. This package will not only make your application run in the background (daemonize) but it will keep on monitoring your code and automatically restarts the server whenever a change is applied using the --watch directive. Install pm2 by using the following command.

# sudo npm install pm2 -g

Start Node.js server using pm2

# sudo pm2 start app.js --name "web-app" --watch

The above command will name this specific process ‘web-app’ (optional) and we can use this name to start or stop the server later.  The --watch directive tells pm2 to reload your app if the source file changes, which is useful for development. You can also run pm2 logs to view log output from your application in realtime.

To daemonize your app (automatically start it when the server starts/reboots) run the following commands:

# sudo pm2 startup
# sudo pm2 save

You only need to run the "startup" command once to generate the startup scripts for pm2 and the save command tells pm2 to save the currently running processes for startup. Read more here.

Now the server will keep running whether you close the terminal or disconnect the instance. You can learn more about pm2 from the official documentation https://pm2.keymetrics.io

Automatically Load Updated SSL Certificates

So now your application is running perfectly but a problem arises when Certbot renews SSL certificates. These certificates are not automatically used by your application and your application keeps on using the old certificates as they are "cached" in a sense.

We can make sure our application uses the latest certificates by using Certbot hooks. We can either use a combination of ‘--pre-hook’ and ‘--post-hook’ or only ‘--deploy-hook’ to restart the server after every successful renewal. In crontab, we will use following cronjob to automatically load updated certificates

0 8 * * *        sudo certbot renew --deploy-hook "pm2 restart web-app --watch"

OR

0 8 * * *         sudo certbot renew --pre-hook "pm2 stop web-app --watch" --post-hook "pm2 start web-app --watch"

The ‘--pre-hook’ will stop the server right before the renewal of certificates and ‘--post-hook’ will start the server again right after the renewal of certificates. The ‘--deploy-hook’ runs only after the successful renewal of certificates. Now every time when certbot renews SSL certificates, server will be restarted by hooks. You can learn more about renewal of SSL certificates by reading the official documentation here

Conclusion

In this article, we have deployed Node.js application on Webdock instance successfully. This application is not only daemonized but it will automatically update itself whenever a change is applied. You can learn more about node.js from official documentation here.

Related articles