The simplest way to run node.js as service use systemd

Written on 13 June 2016

Node deployment series

This post is belong to Node deployment series

Why start Nodejs service use Systemd ?

Systemd is a system and service manager for Linux, compatible with SysV and LSB init scripts. systemd provides aggressive parallelization capabilities.
Systemd is awesome. Yes, it is. It powerful.
Run Nodejs applications as a system service use Systemd help us ensure:
- Node.js service starts automatically.
- Keep node service running after it crash. - Log, and NODE_ENV are support - Easy to monitor. Systemd support log management.

Setup

This is a Systemd config for run Node service. Save this file at /etc/systemd/system/nodeapp.service

[Unit]
Description=Your Node service description go here  
After=network.target

[Service]
Type=simple  
PIDFile=/run/nodeapp.pid  
WorkingDirectory=/path/to/app/  
User=www-data  
Group=www-data  
ExecStart=/usr/bin/node index.js  
Restart=always  
Environment='NODE_ENV=production'  
StandardOutput=null  
StandardError=null  
SyslogIdentifier=ghost  
[Install]
WantedBy=multi-user.target  

Detail of config To ensure that node bin location you type to terminal:

which node  

Result can be /usr/local/bin/node or /usr/bin/node
Then change line to result appear

ExecStart=/usr/bin/node  

Change start file for your are index.js,app.js or server.js ?
Suchas for Ghost is index.js
Then change line to result appear

ExecStart=/usr/bin/node index.js  

All most done.
Start nodeapp service.

systemctl start nodeapp  

Enable it to run on boot up

 systemctl enable nodeapp

See nodeapp service log

journalctl -u myapp  

Now if you done right, your node service up and. You can try to run nodejs web service as backend and Nginx as frontend web server. Let's read Speed up Nodejs Application with Nginx proxy caching