Ubuntu – Systemd .service file not working

nodejssystemd

I'm trying to automatically run the following command on system boot with systemd.

/usr/bin/node /var/www/html/rest-api/dist/index.js

I have verified the command works by running it manually but when I try to initiate it with a rest.service file I'm getting errors.

rest.service:

[Unit]
Description=REST API
After=network.target

[Service]
ExecStart=/usr/bin/node /var/www/html/rest-api/dist/index.js
Restart=always
User=nobody
Group=nobody
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production
WorkingDirectory=/var/www/rest-api/dist

[Install]
WantedBy=multi-user.target

journalctl -u rest-api output:

Where rest.service User & Group = nobody:

Oct 06 02:10:28 ip-172-31-26-208 systemd[7172]: rest-api.service: Failed at step GROUP spawning /usr/bin/node: No such process
Oct 06 02:10:28 ip-172-31-26-208 systemd[1]: rest-api.service: Main process exited, code=exited, status=216/GROUP
Oct 06 02:10:28 ip-172-31-26-208 systemd[1]: rest-api.service: Unit entered failed state.
Oct 06 02:10:28 ip-172-31-26-208 systemd[1]: rest-api.service: Failed with result 'exit-code'.
Oct 06 02:10:29 ip-172-31-26-208 systemd[1]: rest-api.service: Service hold-off time over, scheduling restart.
Oct 06 02:10:29 ip-172-31-26-208 systemd[1]: Stopped REST API. 

Where rest.service User & Group = root:

Oct 06 02:20:11 ip-172-31-26-208 systemd[1]: Started REST API.
Oct 06 02:20:11 ip-172-31-26-208 systemd[1]: rest-api.service: Main process exited, code=exited, status=200/CHDIR
Oct 06 02:20:11 ip-172-31-26-208 systemd[1]: rest-api.service: Unit entered  failed state.
Oct 06 02:20:11 ip-172-31-26-208 systemd[1]: rest-api.service: Failed with  result 'exit-code'.
Oct 06 02:20:12 ip-172-31-26-208 systemd[1]: rest-api.service: Service hold-off > time over, scheduling restart.
Oct 06 02:20:12 ip-172-31-26-208 systemd[1]: Stopped REST API.

Any ideas how to fix?

Best Answer

code=exited, status=200/CHDIR is your key error message.

It indicates that /var/www/rest-api/dist doesn't exist or is not accessible at the time your service is attempting to run.

If it's mounted over the network, After=network.target does not necessarily mean that any given network mount has been mounted. It's even possible that a slow to start local drive might not be mounted yet. To see if you're experiencing a race condition, try adding a delay or possibly using RequiresMountsFor=, or even ConditionPathExists=.

source: https://www.freedesktop.org/software/systemd/man/systemd.unit.html

Related Question