Keywords: Linux | Node.js | Upstart | boot | service | rc.local
Abstract: This article discusses the common issue of Node.js scripts failing to run at system boot when using rc.local. It analyzes the limitations of rc.local and introduces Upstart as a robust alternative for managing daemons. Step-by-step instructions for setting up an Upstart service are provided, along with debugging tips for rc.local.
When developing applications that require automatic execution at system startup, Linux administrators often rely on traditional methods like /etc/rc.local. However, as seen in a common scenario where a Node.js script works manually but fails at boot, this approach can be unreliable.
Limitations of rc.local
The rc.local script runs at the end of the multiuser runlevel, but it may face issues due to environment variables, user context, or timing. For instance, running a script as a specific user like www-data might not set the necessary paths or permissions correctly during boot.
Introducing Upstart
Upstart is an event-based init system used in Ubuntu and other distributions, designed to manage services more effectively. It handles dependencies, logging, and supervision, making it ideal for daemons like Node.js applications.
Setting Up an Upstart Service
To create an Upstart service for the Node.js script, create a configuration file in /etc/init/. For example, /etc/init/my-node-app.conf:
description "My Node.js Application"
author "Your Name"
start on runlevel [2345]
stop on runlevel [016]
respawn
respawn limit 10 5
script
export HOME="/var/www"
exec su -c 'node /var/www/php-jobs/manager.js' www-data
end script
post-start script
echo "Application started at $(date)" >> /var/log/my-node-app.log
end script
This configuration ensures the script runs under the www-data user, respawns on failure, and logs appropriately.
Debugging rc.local
If you need to debug rc.local, you can redirect output and enable command tracing. Add lines like:
exec 1>/tmp/rc.local.log 2>&1
set -x
This logs all output and displays commands before execution, helping identify issues.
Conclusion
While rc.local can work in simple cases, using Upstart provides better reliability and management for services. Transitioning to Upstart or modern alternatives like systemd is recommended for production environments.