How to create and run Node.js applications on CentOS

Node.js, based on Google’s V8 JavaScript engine, the same engine used in Google Chrome, has become a popular platform for developing scalable and efficient server-side JavaScript applications. Software written with Node.js can run on Windows, Mac, and Unix-based servers with the Node.js runtime environment. In this article we’ll walk through the process of installing Node.js on a CentOS server and use the platform to run a sample application.

Node.js is based on the event-driven programming model, which allows a client and a server to initiate asynchronous communication between resources. It is suitable for applications that support highly responsive real-time interaction between a web browser as the client and a web server, such as web chat platforms and online games. Node.js pushes new data from the server to the client without the client having to run a new query, thus avoiding slower HTTP requests and responses. Network applications built on Node.js are scalable and responsive. They work well with large numbers of input and output operations through an event loop mechanism.

To get started with Node.js, first establish an SSH connection to your web server and make sure that the EPEL repository is listed among the repositories for your yum package manager. If it’s not, install it with the commands

wget http://dl.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm
 rpm -ivh epel-release-6-8.noarch.rpm

You can then run the command yum install node.js npm to install Node.js and npm, which is the Node.js package manager, used for installing Node.js programs and related dependencies.

To run a Node.js application on a server that already services web requests through Apache you must apply some modifications. Confirm that mod_rewrite is loaded for your web server by examining the configuration file:

$  grep mod_rewrite /etc/httpd/conf/httpd.conf
 LoadModule rewrite_module modules/mod_rewrite.so

Check under the DocumentRoot directory for your web site and make sure that the AllowOverride value is set to All. Restart Apache if you made changes.

Next, install Express, a Node.js web development tool that you can use with Node.js. Create a new folder for your first Node.js application and install Express under it:

mkdir mynodeapp
 cd mynodeapp/
 npm install express
 ls node_modules/
 express

This installs the Express framework locally, under the ./node_modules subfolder of the Node.js script’s root location (mynodeapp in the above example). This approach is suitable when you use the require() function in your Node.js application’s source code. Otherwise, if you need to call a Node.js tool directly from the command line, add the -g parameter at the end of the command to make the tool globally accessible.

Test the Node.js system by creating the following sample script:

$  cat myapp.js
 var express = require('express');
 var app = express();
 app.get('/', function(req, res){
   res.send('This is my first Node.js script');
 });
 app.listen(7000);

You can then execute the application through the Node.js runtime:

node myapp.js

Load the website followed by the port defined in the application’s code – for example http://mydomain.com:7000/. If everything is working correctly, you should see the message you set in your code displayed in the web browser.

When you deploy an application to a public-facing server you probably want users to open the site directly through the domain without adding a port number at the end. To mask the port number, enter the following lines in the .htaccess file located under the application’s home folder:

RewriteEngine On
 RewriteRule ^(.*)$  http://mydomain.com:7000/$ 1 [P,L]

The first line enables mod_rewrite rules recursively for this web folder. The actual rewrite rule matches every string entered after the domain name and preserves the sub-pattern (surrounded in brackets) in the $ 1 parameter. For example, it will mask the call to the admin URL and visualize it in the web browser as http://mydomain.com/admin instead of http://mydomain.com:7000/admin. It passes the result from the Node.js instance working on port 7000 without adding the actual port to the URL. P stands for proxy, which allows the URLs to be passed through Apache mod_proxy to another server. In our case the web server gets the content that should be substituted (the one from port 7000) and returns it. L stands for last – no more rules are processed for this application.

Ghost installation

Once you know the basics about Node.js setup you can try installing a sample application. Start with Ghost, an open source Node.js script that allows you to quickly build and launch a blog.

First, download the latest application release; as with any application, doing so usually guarantees that all known bugs in previous versions are patched and recently developed features are included. Run the following commands to complete the download and extract the archive to a folder:

mkdir ghost
 cd ghost/
 wget https://ghost.org/zip/ghost-latest.zip
 unzip ghost-latest.zip

Rename Ghost’s configuration file with the command mv config.example.js config.js. Edit the file and change the host occurrences to your IP address (I used 10.10.117.56) and the port occurrences to a chosen port (I used 8005). If you want to use a domain name (for example mydomain.com) to access the blogging application, alter the URL in the file as well. You can leave the other settings intact.

Now run the Ghost installation procedure with the command npm install --production to install only the dependencies for the production mode and skip the ones for a development environment, since you’re not planning to make any changes to the application’s code. You can then start Ghost with the command npm start --production. You should see output similar to:

> [email protected] start /var/www/html/ghost
 > node index
 
 Ghost is running...
 Your blog is now available on http://mydomain.com
 Ctrl+C to shut down

You can load the blog in the web browser by adding the port number after your domain.

Forever

What we’ve done so far is useful for testing your application, but if you terminate the SSH session you’re using to connect to the web server from your local computer, or if you shut down the process by pressing Ctrl-C, the Ghost node will be turned off and the Ghost application will stop working. To keep the application running in the background in production environments you can use forever, a command-line tool that ensures that any Node.js script started with it will work in the background without interruption. Install it globally with the command npm install forever -g, which puts it under /usr/local and therefore lets you call the script directly from the command line. Then start the Ghost index.js file with it.

$  NODE_ENV=production forever start index.js
 warn:    --minUptime not set. Defaulting to: 1000ms
 warn:    --spinSleepTime not set. Your script will exit if it does not stay up for at least 1000ms
 info:    Forever processing file: index.js

In the above command you specify the node environment mode (production or development) and call the forever binary from the command line, followed by the start command and the index file. The warnings appear if you’re using the default forever tool settings, but there is no need to alter them. The last line confirms that the forever tool is taking care for the Ghost’s index.js file processing.

At any time you can list the daemon processes on the server that are running with forever:

$  forever list
 info:    Forever processes running
 data:        uid  command       script   forever pid  logfile                 uptime
 data:    [0] IDzx /usr/bin/node index.js 3706    3708 /root/.forever/IDzx.log 0:0:7:22.172

To hide the port number you can alter the Apache VirtualHost as shown below. (I’m using my own sample data; remember to change your domain, IP address, and port.):

<VirtualHost 10.10.117.56:80>
 ServerName mydomain.com
 ProxyPreserveHost on
 ProxyPass / http://mydomain.com:8005/
 </VirtualHost>

Restart the Apache web server. You should now have a working Ghost blogging application installed on your server. Enter the domain name in your web browser to load it.

In conclusion, if you want to build a fast, event-driven script, Node.js is a tool worth trying. Although it is still maturing and it is difficult to predict how its core features will evolve, it is an exciting new way to develop web-based applications.

Bear in mind, however, that Node.js isn’t suitable for all real-time web applications. For instance, if you expect to use a high percent of CPU resources, as with a video rendering application for example, you should use C++. You might also find it easier to deploy applications written with some PHP frameworks. Finally, you may not be able to use Node.js if your application runs on a shared server where the whole system is tested and configured for average web users, because you might not be able to install the tools and dependencies Node.js needs, or reconfigure the web server to service requests for the platform.