5

Environment: CentOS 8, Node.js, Digital Ocean Droplet

My Systemd setup starts a node app with the following command. It works as expected.

$ sudo systemctl start myapp

File 1: /etc/systemd/system/myapp.service

[Unit]
Description = My App 
After = network.target

[Service]
ExecStart = /root/start-myapp.sh
Restart=on-failure

[Install]
WantedBy = multi-user.target

File 2: /root/start-myapp.sh

#!/bin/sh
/usr/bin/node /srv/myapp/app.js

However when I'm not using Systemd I normally start my app with Node Package Manager using the command, npm start. I'd rather have the Systemd unit also start the app with npm start.

Unfortunately it threw an error when I changed app.js to npm start in /root/start-myapp.sh,

/usr/bin/node /srv/myapp/npm start

I made another attempt by switching the path from node to npm but it produced the same error.

/usr/bin/npm /srv/myapp/npm start

Question: How do I get my Systemd unit file to start my app with the command npm start?

3 Answers 3

10

I'm running a similar setup on Debian, and my service looks like this:

...

[Service]
Environment=NODE_PORT=3000
Type=simple
User=www-data
Restart=on-failure
WorkingDirectory=/var/www/<your-code-directory>
ExecStart=npm start

...

Hope this helps!

3

I didn't have luck with filipe's answer but I found this one that is very close!

[Unit]
Description=My application

[Service]
Type=simple
Restart=always
User=nobody
Group=nobody
WorkingDirectory=/opt/myapplication
ExecStart=/usr/bin/npm start

[Install]
WantedBy=multi-user.target

A major difference being the ExecStart has /usr/bin/ preceeding the npm start. The other is that it excludes the environment, I added a port flag to mine so npm start --Port 5000

I also found this to be a useful article pertaining to setting up services if you're extremely new to it like myself.

It doesn't cover the question but does have some other useful tips.

I was also on Centos 7

0

if you manually exec npm start and you check ps -ef | node you will find what actually executing, that is node. Node is the only executable that runs everything. I'll give you an example:

/home/ubuntu/.nvm/versions/node/v18.16.0/bin/node /home/ubuntu/aiphotoviewer/node_modules/.bin/next start

Your node will be in another location but same concept. Just npm run, ps -ef | node to check the actual running process and copy it and you're good to go

Hope it help.

P.S. maybe i'm too late? it's been 2 years...

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .