Run node processes with systemd

14 Jul 2021 in TIL

I used to reach for supervisord to keep Node.js services running, but today I decided to try out systemd. Here's how to do it (I was running on an Ubuntu EC2 instance on AWS):

Create a file at /lib/systemd/system/my_app.service with the following contents:

bash
[Unit]
After=network.target
[Service]
Type=simple
User=ubuntu
ExecStart=/usr/bin/node /path/to/app/index.js
Restart=on-failure
[Install]
WantedBy=multi-user.target

Reload to pick up any changes to the .unit files:

bash
sudo systemctl daemon-reload

Finally, start the process:

bash
systemctl start my_app

At this point I can kill the process with kill -9 and it respawns almost instantly.