Grid Guides

Explore How System On Grid Can Work For You

Grid Guide Topics

How to Setup a Node.js Application for Production on Ubuntu 18.04

Table Of Contents


    ## Table of Contents

    – [Introduction](#introduction
    – [Prerequisites](#prerequisites
    – [Setup a Node js Application](#set-up-a-node-js-application
    – [Install Node js](#install-node-js
    – [Create a Node js Application](#create-a-node-js-application
    – [Install PM2](#install-pm2
    – [Setup Nginx as a Reverse Proxy Server](#set-up-nginx-as-a-reverse-proxy-server
    – [Conclusion](#conclusion

    ## Introduction

    In this guide, we will explain to you how to set up a Node.js application for production on Ubuntu 18.04.

    [Node.js](https://nodejs.org/en/about/ is an open source, asynchronous event-driven JavaScript runtime environment that executes JavaScript code on server side. Node.js is used to create web servers, networking tools, and applications using the JavaScript Code. It is supported on operating systems like Microsoft Windows, Linux, macOS, smartOS, IBM AIX, and FreeBSD. It opened the doors for creating fast and highly scalable web servers without using threads, by using a simplified model of event-driven programming.

    ## Prerequisites

    You should have access to an Ubuntu 18.04 server and created a non-root user account with sudo privileges by following our guide, [Initial server setup with Ubuntu 18.04](https://systemongrid.com/guides/how-to-do-initial-server-setup-with-ubuntu-18.04.
    You should have installed nginx, as we discussed in [How to Install Nginx on Ubuntu 18.04](https://systemongrid.com/guides/how-to-install-nginx-on-ubuntu-18.04.
    You should have a server serving your domain’s default placeholder page at [www.example.com](http://example.com/.

    ## Setup a Node js Application

    ## Install Node js

    Install the latest release of Node.js from the NodeSource package archives.

    Then, install the NodeSource PPA to get access to its contents.

    Retrieve the installation script for the Node.js 8.x archives using curl command.

    “`
    $ cd ~
    $ curl -sl https://deb.nodesource.com/setup_8.x -o nodesource_setup.sh
    “`

    Inspect the contents of the script using nano or use your preferred text editor.

    “`
    $ nano nodesource_setup.sh
    “`

    Then, run it with sudo command.

    “`
    $ sudo bash nodesource_setup.sh
    “`

    Now, The PPA will be added to your configuration, your local package cache will be updated automatically.

    Now, install Node.js package.

    “`
    $ sudo apt install nodejs
    “`

    Check the version of the Node.js using the following command.

    “`
    $ nodejs -v
    “`

    Output:

    ![nodejsversion](https://grid.media/assets/images/nodejs-version.png

    And, you don’t need to npm, a package manager for Node modules, separately as the Node.js package contains Node.js binary and npm also.

    To keep track of updates, npm uses a configuration file, created when you run npm for the first time, in your home directory.

    Use the following command to check whether npm is installed and created the configuration file.

    “`
    $ npm -v
    “`

    Output:
    ![npm](https://grid.media/assets/images/npm.png

    Install build-essential package using the below command to make some packages to work.

    “`
    $ sudo apt install build-essential
    “`

    Now, you have all the necessary packages to work with npm packages.

    Then, start writing a Node.js application with the Node.js runtime installed.

    ## Create a Node js Application

    We are creating a sample Node.js application to explain you the process.

    Let the name of it be, Hello SystemOnGrid that return Hello SystemOnGrid to any HTTP request.

    Replace it with your application and make sure it is listening on the appropriate IP addresses and ports.

    Let’s create a sample application called, hello.js:

    “`
    $ cd ~
    $ vim hello.js
    “`

    Copy and paste the following code into the file.

    “`
    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 SystemOnGrid!n’;
    };

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

    Save the file and exit.

    The Node.js application listens on the specific address – localhost, and Port – 3000 and returns “Hello SystemOnGrid” with an HTTP code – 200. As we are listening on localhost, remote users can’t connect to our application.
    Now, test your application with the following command.

    “`
    $ node hello.js
    “`

    You will get the following output.

    Output:

    ![testnodejs](https://grid.media/assets/images/test-node.js.png

    Now, to test your application, open another terminal and connect to localhost with curl.

    “`
    $ curl http://localhost:3000
    “`

    You will get the following output.

    Output:
    ![hellosystemongrid](https://grid.media/assets/images/hello-systemongrid.png

    If you get the above output, your application is working correctly and listening on appropriate address and port.

    Kill the application using CTRL+C after you are sure that it is working correctly.

    ## Install PM2

    Install PM2, a process manager for Node.js applications, to make applications keep running in the background as a service.

    You can install the latest PM2 using npm command.

    “`
    $ sudo npm install pm2@latest -g
    “`

    Use PM2 start command to run the application, hello.js, in the background.

    “`
    $ pm2 start hello.js
    “`

    This also adds the application to the process list of PM2, which you will get as an output every time you start the application.

    ![pm2](https://grid.media/assets/images/pm2.png

    If the application is killed or crashed, all the applications that are running under PM2 will be restarted automatically. But, we can get the application to launch on a system using startup subcommand.

    The subcommand will generate and configure a startup script to launch PM2, its managed processes on server boots.

    “`
    $ pm2 startup systemd
    “`

    To set PM2 to start on boot, the last line of the output will have a command to run with superuser privileges.

    Output:
    ![startupsysstemd](https://grid.media/assets/images/startup-systemd.png
    ![superuserprivileges](https://grid.media/assets/images/superuser-privileges.png
    Run the command with your username in the place of systemongrid.

    “`
    $ sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u systemongrid –hp /home/systemongrid
    “`

    Now, save the PM2 process list and corresponding environments.

    “`
    $ pm2 save
    “`

    You have created a systemd unit which runs PM2 for your server on boot. The PM2 instance runs hello.js.

    Start the service using systemctl:

    “`
    $ sudo systemctl start pm2-systemongrid
    “`

    Check the status of the systemd unit using the command:

    “`
    $ systemctl status pm2-systemongrid.service
    “`

    PM2 also provides many subdomains that allow you to manage or get more information about your applications. You can stop any application, say hello.js2, using the command:

    “`
    $ pm2 stop hello.js2.
    “`

    To restart applications, use the command:

    “`
    $ pm2 restart hello.js2
    “`

    To know the list of applications currently managed by PM2, use the command:

    “`
    $ pm2 list
    “`

    To get information about a specific application, use the command:

    “`
    $ pm2 info hello.js2
    “`

    To pull up the PM2 process monitor, use the subcommand:

    “`
    $ pm2 monit
    “`

    Now, your Node.js application is running and managed by PM2.

    ## Setup Nginx as a Reverse Proxy Server

    Now, you need to set up a way for your users to access your application as it is running and listening on localhost. To do so, you can set up Nginx as a reverse proxy server.

    To install NGINX package execute below command

    “`
    $ sudo apt-get install nginx
    “`

    Open your Nginx configuration in the /etc/nginx/sites-available/example.com file.

    “`
    $ sudo vim /etc/nginx/sites-available/example.com
    “`

    You must have an existing location block within the server block, replace it with the following configuration.

    Update the port number if your application is set to listen on a different one.

    “`
    /etc/nginx/sites-available/example.com

    server {

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

    }
    “`

    This makes the server to respond to requests at its root.

    Now, let us assume that our server is available at example.com and accessing via https://example.com via browser would send a request to your application, hello.js, listening on port 3000 at localhost.

    You can also add additional location blocks to the same server block for providing access to other applications on the same server.

    If you were running your another Node.js application on port 3001, you could add the location block to give access to it via https://example.com/hello.js2.

    “`
    /etc/nginx/sites-available/example.com — Optional

    server {

    location /hello.js2 {
    proxy_pass http://localhost:3001;
    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 the file and exit.

    To check whether you have introduced any syntax errors, use the following command:

    “`
    $ sudo nginx -t
    “`

    Now, restart Nginx using the command:

    “`
    $ sudo systemctl restart nginx
    $ sudo service nginx restart
    “`

    Now, you can access your application through the Nginx reverse proxy server.

    ## Conclusion

    Now, You have your Node.js application running a Nginx reverse proxy server on an Ubuntu 18.04 server.