Creating Persistent Node.js Applications

Node.js applications on shared and reseller servers may be periodically terminated for security and performance reasons. This guide explains how to keep your Node.js application running using either the Node.js Selector in cPanel (preferred) or a cron job.


Methods to Maintain a Persistent Node.js Application

There are two ways to ensure your Node.js application remains active:

  1. Node.js Selector in cPanel (Preferred Method)
    The Node.js Selector maintains the running state of your application and provides an interface to start, stop, or restart it. This is the recommended approach for cPanel shared and reseller servers.
    For detailed instructions, refer to the Node.js Selector documentation in cPanel.

  2. Cron Job (Manual Setup Required)
    Use a cron job if you have manually created a Node.js application and cannot use the Node.js Selector (e.g., if your app needs to run on a specific port). Tools like PM2 or Forever will not work because their processes are subject to periodic termination on these servers.


Setting Up a Cron Job to Keep Node.js Running

Important: Ensure Node.js is already installed on your account before proceeding.

  1. Log in to cPanel
    If you need guidance, refer to the cPanel login documentation.

  2. Access Cron Jobs
    In the ADVANCED section of the cPanel home screen, click Cron Jobs.

  3. Set Up Cron Email
    Under Cron Email, enter the e-mail address where notifications should be sent and click Update Email.
    Optional: To disable e-mail notifications for a specific cron job, append >/dev/null 2>&1 to the cron command.

  4. Add a New Cron Job

    • Under Add New Cron Job, set the interval. To ensure maximum uptime, run the cron job every 15 minutes:

      • In Minutes, type */15 or select Once per Fifteen Minutes (*/15).

      • No other time settings are needed.

    • In Command, type the following, replacing mylock, app_directory, and startup_file with your application's values:

    /usr/bin/flock -n /tmp/mylock.lock ${HOME}/nodejs/bin/node ${HOME}/app_directory/startup_file.js

    Explanation:
    The flock command checks whether the Node.js instance is already running before starting a new one. This prevents port conflicts and ensures only one instance runs at a time.

  5. Save the Cron Job
    Click Add New Cron Job. cPanel will create the cron job, which will now periodically restart your Node.js application if it terminates.


This setup ensures your Node.js application remains running with minimal downtime, even on shared or reseller hosting environments.

Bu cavab sizə kömək etdi? 0 istifadəçi bunu faydalı hesab edir (0 səs)

Powered by WHMCompleteSolution