Node.js in production with systemd

By Evasive Software
On March 20, 2017
In Blog

Despite systemd being controversial in the Linux community, I am happy to recommend using it as a service manager for Node.js server applications.

Having the power of systemctl at your fingertips makes starting, stopping, logging, and other general operations a breeze for your Node.js server.

A basic systemd service for your Node.js server

The syntax is very similar to that of a .ini (Yes, just like those old Windows configuration files you used to modify).

Modify the template below to suit your application. Be sure to set User and Group to a real user and group on your server. Your Node.js application will be running as this user and group, so ensure it’s secure.

The service file template

[Unit]
Description=My Node.js server application

[Service]
ExecStart=/opt/path/to/nodeapp/server.js
Restart=always
User=nodeuser
Group=nodegroup
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production
WorkingDirectory=/opt/path/to/nodeapp

[Install]
WantedBy=multi-user.target

Installing the service file

Research where your distribution expects to find systemd service files, and save your new service file there. On Debian, you can save it in /etc/systemd/system/nodeapp.service

Also, ensure your new service file is executable.
chmod +x /etc/systemd/system/nodeapp.service

Controlling your new systemd service

You can test and control your new service utilising the systemctl tool.

To start your service
systemctl start nodeapp.service

To stop your service
systemctl stop nodeapp.service

To restart your service
systemctl restart nodeapp.service

Enable your service for automatic launch on boot_
systemctl enable nodeapp.service

Disable your service for automatic launch on boot
systemctl disable nodeapp.service

Conclusion

You should now be convinced that systemd can be a powerful, yet simple tool for managing services on Linux.

You should read the documentation to gain a deeper understanding of the inner workings and the best practices recommended for systemd usage.

Blog comments powered by Disqus