Skip to content

Instantly share code, notes, and snippets.

@xeptore
Last active July 27, 2018 07:13
Show Gist options
  • Save xeptore/8d2d37bae12bcc6bf30fb5a0cc281b6a to your computer and use it in GitHub Desktop.
Save xeptore/8d2d37bae12bcc6bf30fb5a0cc281b6a to your computer and use it in GitHub Desktop.
Nodejs always running process as a linux service

Help


  • Replace with the user you want to command get executed by. to find your current user execute this command:
whoami
  • ExecStart is the command you want to get executed in the WorkingDirectory. for example assume server.js file exists in previously specified WorkingDirectory. then weyou should set ExecStart to: ExecStart=/usr/bin/node server.js

  • Environment is the environment variables you want to set before executing command. for example the following Environments: Environment=PORT=8080 Environment=DB=production will set two PORT and DB environments to 8080 and production respectively.

Conclusion:


Final result of created example service equals with execution of the following commands by user: :

cd /home/<USER>/<DIRECTORY_TO_EXECUTE_COMMANDS_IN>/;
export PORT=8080;
export DB=production;
/usr/bin/node server.js;

Finally execute following commands:

sudo systemctl enable nodejs_server;
sudo systemctl start nodejs_server;

And you can run following command to see your newly created service status:

sudo systemctl status nodejs_server;
[Unit]
Description=Node.js Server
[Service]
PIDFile=/tmp/node-running-server-99.pid
User=<USER>
Group=<USER>
Restart=always
StandardOutput=syslog
StandardError=syslog
KillSignal=SIGQUIT
WorkingDirectory=/home/<USER>/<DIRECTORY_TO_EXECUTE_COMMANDS_IN>/
ExecStart=/usr/bin/node server.js
Environment=PORT=8080
Environment=DB=productio
[Install]
WantedBy=multi-user.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment