0

I have nodejs server that generate by express-generator. Now i try to create systemd service to run my server.

[Unit]
Description=Node.js Example Server     

[Service]
ExecStart=/usr/bin/node /opt/nodeserver/server.js
Restart=always
StandardOutput=syslog               
StandardError=syslog                
SyslogIdentifier=nodejs-example
Environment=NODE_ENV=production PORT=1337

[Install]
WantedBy=multi-user.target

The service can not run because i cant run the server with the command node server.js. The only way i can run the server: npm server.js. How can i tell the service run the server with npm command and not node?

rontoDay
  • 53
  • 1
  • 1
  • 4
  • Did [my answer](http://stackoverflow.com/questions/40861258/create-systemd-nodejs-express-generator/40863613#40863613) help? Any comments? – rsp Dec 01 '16 at 09:49

1 Answers1

0

Systemd can be sometimes problematic. It's easier to write SysV or Upstart init scripts whenever you can. I explain some of the issues in those answers: [1], [2].

Now, what you can do is to write a startup script yourself that would:

  1. change the working directory to your application
  2. run the start command

For example:

#!/bin/sh
cd /your/application/path
npm start

(or npm server.js or whatever your command is instead of npm start)

It may also be useful to set the correct PATH if you need it:

#!/bin/sh
PATH="/opt/node/bin:$PATH"
export PATH
cd /your/application/path
npm start

(where /opt/node/bin is where your node and npm are installed)

If you save such a script as e.g. /opt/nodeserver/server.sh then you should be able to use:

ExecStart=/bin/sh /opt/nodeserver/server.sh

in your systemd script (unless there are more gotchas in systemd that would cause problems here).

Community
  • 1
  • 1
rsp
  • 107,747
  • 29
  • 201
  • 177