Running Node.js Application on Managed Hosting
By: A. S. Md. Ferdousul Haque
Tags: NPM, JavaScript, Hosting, Serverless, Nodejs

Javascript is now a days everywhere from frontend to backend, from earth to outer space, even it have a wide range of usability web development to full fledged application.

The JS game changed once nodejs came to cover the server side compiling. As nodejs is a server side language, it needs to be hosted in a place, where it can compile and render output. Due to the fact that nodejs is a single threaded application, you can use the CPU threads at best. Let’s consider you are making a REST API in nodejs and some mobile application will use this API from outside. You will need to host the application to a web hosting where it will run forever, options are AWS[EC2], DigitalOcean[Droplet] as you need to install few packages to run the node application and may require superuser [root] privilege. These options are a bit complex as you need to manage the host as well and it is also expensive for a startup company to afford. Another option available are for serverless application hosting like AWS Lambda, Heroku etc. You will be charged on the hit count base and initially comes with a lot of free hits until the threshold is reached for the month.

Another option available, which is using the managed hosting for the nodejs application. Most of us already have managed hosting for personal website or any other cases as it is cheap and we have a lot of resellers for the hosting services. We may have a misconception that we need to have superuser [root] access or unmanaged host for running nodejs application. However, hosting providers usually provides jailshell or basic shell like [bash, zsh, sh] and using only shell access, we can deploy nodejs application in the managed hosting.

Here, I will try to clear the dogma. I will demonstrate how you can use nodejs application on a managed host, without even root access. Just login to the SSH of the host and follow the below steps 😛.

Prerequisites:

First confirm you have shell access. To confirm this run the below command.

echo $SHELL

If you have access to shell it will return like /bin/bash or /bin/zsh or /bin/sh. If you are getting something else, means you are using jailshell. Ask your hosting provider to change this.

Installation:

Next we are going to install nodejs in the hosting account. with the following steps.

Login to your hosting account using SSH.

At the command prompt run the following command:

To extract the nodejs files, type the following command and rename the extracted folder to the more convenient nodejs name, type the following command:

tar xvf node-v14.15.3-linux-x64.tar.xz

mv node-v14.15.3-linux-x64 nodejs

Here we will create a bin directory inside our shell and copy the node binary and softlink the npm to the bin directory.

mkdir ~/bin

cp nodejs/bin/node ~/bin

cd ~/bin

ln -s ../nodejs/lib/node_modules/npm/bin/npm-cli.js npm

And you are done installing nodejs on the managed hosting. Now run these commands to verify this, type the following commands:

node --version

npm --version

Starting Application:

#1: Using npm:

For this method to work, there must be a valid package.json file for the application. The package.json file contains project metadata that the npm program reads to determine how to start the application, manage its dependencies, and more.

nohup npm start --production &

The & places the command in the background, and the nohup command ensures that the application continues running even if you log out of the current terminal session.

#2: Running node directly:

For simple applications, or for any application that does not have a package.json file, you can run the node executable directly and specify the application filename. For example:

nohup node app.js &

For stopping a Node.js application, you need to kill node applications.

pkill node

#3: Production ready application:

For a production ready application, you would not like to take risk by running in a single thread without any fallback processes. Hence you should use pm2 for using the most of your CPU threads and memory, it will handle if one thread fails and restart automatically and use npm to orchestrate. So you need to install one npm package.

npm install -g pm2 pm2-logrotate

Here installed pm2-logrotate because pm2 will generate logs and if not rotated then it may cause disk space issues.

next create config files for pm2 in yaml. Here is one sample for this.

apps:

- script: server.js

name: web-api

max-memory-restart: 200MB

instances: 2

exec_mode: cluster

Here means, it will run the server.js file located in the directory and it will create 2 application instances and run in a cluster mode. In case any memory leakage above 200MB it will automatically restart the application and when you list the running processes it will show web-api.

Now add the following lines in your package.json file and run the application from npm.

"scripts": {

"preinstall": "npm install",

"dev": "node server.js",

"start": "pm2 start web-api.yaml",

"test": "jest --coverage --verbose",

"stop": "pm2 stop web-api",

"clear": "pm2 delete web-api",

"list": "pm2 list",

"logs": "pm2 logs"

}

Initially run the npm install and then you can run the development mode until you finish with development.

npm run dev

Now you can run and stop your application in cluster mode with the following commands.

npm run start

npm run stop

To see the logs and list of processes run the following command

npm run logs

npm run list

Integrating your nodejs application with the web server

Depending on the type of nodejs application you are running, you may want to be able to access it using a web browser. To do this, you need to select an unused port for the Node.js application to listen on, and then define server rewrite rules that redirect visitors to the application. The following steps demonstrate how to do this.

In a text editor, add the following lines to the .htaccess file in the /home/username/public_html directory, where username represents your account username. If you want to change the directory inside public_html it is also possible.

DirectoryIndex disabled

RewriteEngine On

RewriteRule ^$ http://127.0.0.1:{Port}/ [P,L]

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ http://127.0.0.1:{Port}/$1 [P,L]

These rewrite rules redirect incoming HTTP visitor requests to the Node.js application running locally on the server. 127.0.0.1 is the loopback address for localhost.

2. In both RewriteRule lines, replace {Port} with the port on which your Node.js application listens. To run a Node.js application on a managed server, you must select an unused port between 30000 and 50000 (inclusive).

3. Save the changes to the .htaccess file, and then exit the text editor. Visitors to your web site are redirected to the Node.js application listening on the specified port.

Troubleshoots: #01 If your application fails to start, the port you chose may already be in use. Check the application log for error codes like EADDRINUSE that indicate the port is in use. If it is, select a different port number, update your application’s configuration and the .htaccess file, and then try again. #02 If you are not able to call the API from the application then it may be the case of OPTIONS method permission is not allowed to your hosting, which is required for cross-origin API calls. You can ask to allow by creating one support ticket to your hosting provider.

Long article huh !! finished. Now go to your web browser and hit the URL and viola.