Node.js
Automatically start forever node on system restart
Ensuring your Node.js applications remain online and operational is paramount for any production environment. Unexpected server reboots, system updates, or even application crashes can lead to downtime, impacting user experience and potentially revenue. This is where robust process management becomes critical, especially the ability to automatically start forever (node) on system restart. Manually restarting applications after every server event is not only impractical but also prone to human error. This guide delves into the essential techniques and tools, primarily focusing on forever in conjunction with system-level services, to guarantee your Node.js processes are always running, even after an unforeseen system reboot. We’ll explore how to set up your Node.js applications for maximum uptime, providing a foundation for reliable and scalable deployments.
Understanding the Need for Process Management in Node.js
Node.js applications, by their very nature, are single-threaded and can crash due to uncaught exceptions, memory leaks, or external factors. Without a robust process manager, such crashes would leave your application offline until a manual intervention. Imagine a critical API service failing during peak hours; the financial and reputational damage could be substantial. This is why tools designed for Node.js process management are indispensable.
A process manager acts as a supervisor, monitoring your application, restarting it if it crashes, and ensuring it starts automatically when the system boots up. This significantly improves application uptime and reliability. While simple scripts might suffice for development, production environments demand sophisticated solutions that can handle logging, resource monitoring, and graceful restarts. Neglecting proper process supervision can lead to unstable services and unnecessary operational overhead.
The challenge extends beyond just crash recovery; it’s also about maintaining continuity through server lifecycle events. Whether it’s a planned maintenance reboot or an unexpected power outage, your application needs to be resilient. Implementing a strategy to daemonize Node.js apps ensures they run in the background as services, detached from the user session that launched them, making them suitable for continuous operation.
Introducing Forever: A Robust Solution
forever is a simple and effective command-line interface (CLI) tool that ensures a given script runs continuously. It’s particularly useful for smaller Node.js deployments where the overhead of more complex process managers like PM2 might be overkill. Forever monitors your Node.js script, and if it crashes for any reason, it automatically restarts it, providing a crucial layer of stability for your applications.
Installing forever is straightforward via npm, the Node.js package manager. Once installed globally, you can easily start your Node.js application using forever start app.js. This command detaches the process from your terminal, allowing it to run in the background. It also provides logging capabilities, capturing stdout and stderr to specified files, which is vital for debugging and monitoring your application’s health. For developers seeking a quick and reliable way to daemonize Node.js apps, forever offers an excellent balance of simplicity and functionality.
While forever handles application crashes, it doesn’t inherently manage system reboots. This is where its integration with system-level process supervisor tools becomes essential. For instance, combining forever with systemd on Linux systems allows you to leverage the operating system’s capabilities to ensure your Node.js application, managed by forever, springs back to life immediately after a server restart. This two-pronged approach provides comprehensive uptime assurance for your services.
To truly automatically start forever (node) on system restart, you need to integrate it with your operating system’s init system. On modern Linux distributions, this is typically systemd. By creating a systemd service unit file, you can instruct the operating system to start your forever-managed Node.js application as a background service every time the system boots up. This method provides a robust and officially supported way to ensure continuous operation.
For those needing to guarantee their Node.js applications are always running, even after a server reboot, configuring a systemd service is the most reliable approach. This method treats your application as a core Linux service, allowing it to be managed, monitored, and restarted by the operating system itself. It’s a standard practice in professional deployments to ensure application uptime and stability.
A systemd service file explicitly defines how your application should be started, stopped, and managed. This includes specifying the user and group under which the process runs, its working directory, and the command to execute. When properly configured, if your server reboots, systemd will automatically execute the command to start forever, which in turn will launch your Node.js application, ensuring minimal downtime.
Step-by-Step: Creating a Systemd Service for Forever
Here’s how to set up a systemd service to manage your Node.js application with forever:
-
**Create a Service Unit File:**Open a new file for your service unit. For example,
sudo nano /etc/systemd/system/myapp.service.The content of this file should look something like this:
[Unit] Description=My Node.js App Service After=network.target [Service] Type=simple User=your_user_name WorkingDirectory=/path/to/your/app ExecStart=/usr/bin/forever start -c "node --expose-gc" app.js Restart=always RestartSec=3 StandardOutput=syslog StandardError=syslog SyslogIdentifier=myapp [Install] WantedBy=multi-user.targetRemember to replace
your_user_name,/path/to/your/app, andapp.jswith your actual values. TheExecStartcommand tells systemd to useforeverto start your application, andRestart=alwaysensures it restarts on crashes. You can find more details on systemd service unit configuration. -
**Reload Systemd and Enable the Service:**After creating or modifying the service file, you need to tell systemd to reload its configuration:
sudo systemctl daemon-reloadThen, enable your service to start on boot:
sudo systemctl enable myapp.serviceQuestion & Answer :
I am using node’s forever module to keep my node server running. Forever however terminates when there is a system restart. Is there any way I can automatically start the node server (with forever) when the system restarts?I would suggest using crontab. It’s easy to use.
How to
-
To start editing run the following replacing the “testuser” with your desired runtime user for the node process. If you choose a different user other than yourself, you will have to run this with sudo.
$ crontab -u testuser -e -
If you have never done this before, it will ask you which editor you wish to edit with. I like vim, but will recommend nano for ease of use.
-
Once in the editor add the following line:
@reboot /usr/local/bin/forever start /your/path/to/your/app.js -
Save the file. You should get some feedback that the cron has been installed.
-
For further confirmation of the installation of the cron, execute the following (again replacing “testuser” with your target username) to list the currently installed crons:
$ crontab -u testuser -l
Note that in my opinion, you should always use full paths when executing binaries in cron. Also, if the path to your forever script is not correct, run
which foreverto get the full path.Given that
forevercallsnode, you may also want to provide the full path tonode:@reboot /usr/local/bin/forever start -c /usr/local/bin/node /your/path/to/your/app.jsFurther Reading
-