Deploying Node.js App on Shared Web Hosting: A Comprehensive Guide

Deploying Node.js App on Shared Web Hosting: A Comprehensive Guide

Introduction

In this blog post, we will walk through the step-by-step process of deploying your Node.js app on shared web hosting, ensuring a smooth and hassle-free deployment. Whether you have access to Cpanel or need to utilize SSH, this guide has got you covered. We'll also address potential challenges and offer solutions to ensure your application remains up and running. So, let's dive in!

Prerequisites

Before we begin, make sure you have the following:

  1. Access to Cpanel

  2. Active Internet connection

  3. Error-free Node.js app working perfectly on your local machine

  4. Patience and enthusiasm to overcome any challenges along the way

Step-by-Step Guide

a. Login to Cpanel and open the Web Terminal (If Web Terminal is not available, follow steps b to d)

b. Login to your web hosting provider and check for settings like "manage hosting." Click on the server and ensure that SSH access is turned on. Note down the credentials.

c. Install a tool like PuTTY to connect to the server using SSH.

d. Use the provided host (IP address or domain name) and the associated port number to establish a connection using PuTTY.

e. In the terminal, execute the following command:

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash

The above command installs nvm, a version manager for Node.js. You can find more information about nvm on its GitHub repository (https://github.com/nvm-sh/nvm#install-script).

f. Now comes the crucial step of installing the correct Node.js version supported by your hosting environment. Run the command:

nvm ls-remote

This command will display the available Node.js versions.

g. Install the desired Node.js version using either of the following commands:

  • To install the latest version:
nvm install node
  • To install a specific version (replace <version> with the desired version number):
nvm install <version>

h. If you encounter any errors while installing or running your app with a specific Node.js version, consider downgrading to the previous version. You can uninstall the current version using:

nvm uninstall <version>

i. Upload the zip file of your Express app into the public_html folder on your shared web hosting. You may delete any existing files if necessary, but ensure not to delete the .htaccess file.

j. Extract the contents of the zip file into the public_html folder, making sure that the package.json file is located in the public_html folder.

k. Change the directory to the public_html folder in the terminal and run the following command to install the required packages:

npm install

l. Modify the .htaccess file either through the file manager or the terminal using your preferred method. Update the file to include the following content:

RewriteEngine on
RewriteRule ^index.html.var$ http://localhost:3000/$1 [L,P,QSA]
RewriteRule  (.*)  http://localhost:3000/$1  [P,L]

m. While in the public_html folder in the terminal, run the command node index.js (replace index.js with your main Node.js file) to start your app. You should now see your site live.

n. By default, quitting the terminal will shut down your app. To prevent this, run the app using the following command instead:

node index.js &

This command allows the app to run in the background.

o. However, if you experience issues with the app shutting down every few days, we recommend following these additional steps:

p. Install PM2 globally by running the command:

npm install pm2 -g

q. Create a new file named ecosystem.config.js in the public_html folder. This file will contain environment variables and configuration settings for PM2. Use the following code as a starting point and adjust it to fit your specific requirements:

module.exports = {
  apps : [{
    script: '/home/<username>/public_html/index.js',
    watch: false,
    env: {
      USERNAME: 'some@example.com',
    },
  }],
  deploy : {
    production : {
      user : 'SSH_USERNAME',
      host : 'SSH_HOSTMACHINE',
      ref  : 'origin/master',
      repo : 'GIT_REPOSITORY',
      path : 'DESTINATION_PATH',
      'pre-deploy-local': '',
      'post-deploy' : 'npm install && pm2 reload ecosystem.config.js --env production',
      'pre-setup': ''
    }
  }
};

r. Create a new file named script.sh in the root directory and add the following content: Replace username and version with actual username and version.

#!/bin/bash
PATH=$PATH:/home/<username>/.nvm/versions/node/<version>/bin 
export TZ=Asia/Kolkata
status=$(pm2 show index | awk '/status/ {print $4}')
if [ "$status" == "online" ]; then
  echo "Process is running."
else
  echo "$status" >> output.txt
  echo "Process is not running." >> output.txt
  current_time=$(date +"%Y-%m-%d %T %Z")
  pm2 start /home/<username>/public_html/ecosystem.config.js 2>> output.txt
  echo "Started at: $current_time" >> output.txt
fi

s. Set up a cron job that runs the above script every minute. Add the following entry to your crontab:

* * * * * sh /home/<username>/script.sh

Ensure you replace <username> with the actual username and make any necessary changes to the paths.

Conclusion

Congratulations! You have successfully deployed your Node.js application on shared web hosting. This step-by-step guide has equipped you with the knowledge to overcome the challenges associated with deploying Node.js apps on shared hosting environments. By following these instructions and utilizing tools like PM2, you can ensure that your app remains up and running, providing a seamless experience for your users. Happy coding!

Remember, deploying Node.js apps on shared hosting can vary depending on the hosting provider and their specific configurations. It's always a good idea to consult the hosting provider's documentation or support if you encounter any difficulties during the deployment process.

By implementing the steps outlined in this guide, you can deploy your Node.js app confidently, knowing that it will run smoothly on shared web hosting.