Node.js as a background service

N

When you are developing and testing your application, it’s ok to constantly start the Node.js server; however, once you’ve finished or you are trying to setup a production web server you want the Node.js service to always be running in the background. Let’s explore the variety of ways to accomplish this.

Node.js as service

This article will explore how to setup Node.js for Linux distros and OSX. For Linux I will systemd as this is supported by most Linux distro. For OSX I will use launchd.

Node.js with systemd

You will need one file for each Node.js application you plan on running. Begin by creating a new file in this folder: /etc/systemd/system. I suggest naming your file the name of your with the extension .service. E.g. endyourif.service

[code]
[Unit]
Description=EndYourIf

[Service]
ExecStart=/var/www/endyourif/app.js
Restart=always
User=nobody
Group=nogroup
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production
WorkingDirectory=/var/www/endyourif

[Install]
WantedBy=multi-user.target
[/code]

In the above code sample you will need to change the ExecStart and WorkingDirectory to where your application resides.

To start your application, run the following command: systemctl start endyourif.
To run your application on server startup, run the following command: systemctl enable endyourif.

Node.js with launchd

You will need one file for each Node.js application you plan on running. Begin by creating a new file in this folder: Library/LaunchDaemons. I suggest naming your filename as follows: www.endyourif.application.plist.

[code]
<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE plist PUBLIC “-//Apple//DTD PLIST 1.0//EN” “http://www.apple.com/DTDs/PropertyList-1.0.dtd”>
<plist version=”1.0″>
<dict>
<key>Label</key>
<string>www.endyourif.application</string>

<key>WorkingDirectory</key>
<string>/www/endyourif</string>

<key>ProgramArguments</key>
<array>
<string>/usr/local/bin/node</string>
<string>app.js</string>
</array>

<key>RunAtLoad</key>
<true/>

<key>KeepAlive</key>
<true/>

</dict>
</plist>
[/code]

You will need to update the Label, WorkingDirectory, and ProgramArguments as required.

To start and enable your application run the following commands: launchctl load /Library/LaunchDaemons/www.endyourif.application.plist and launchctl start /Library/LaunchDaemons/www.endyourif.application.plist.

About the author

By Jamie

My Books