Skip to content

Instantly share code, notes, and snippets.

@iPublicis
Last active March 26, 2024 21:06
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iPublicis/88ddfed0c6ed73ab44de852fcb84750f to your computer and use it in GitHub Desktop.
Save iPublicis/88ddfed0c6ed73ab44de852fcb84750f to your computer and use it in GitHub Desktop.
NODE.JS app as a systemd service with CI controller
#########
# File: myapp-node-watcher.path
#
# Save this to /etc/systemd/system/
# Run systemctl enable myapp-node-watcher.path && systemctl daemon-reload && systemctl start myapp-node-watcher.path
#
[Path]
PathModified=/home/myuser/myappdir/public_html
[Install]
WantedBy=multi-user.target
#########
# File: myapp-node-watcher.service
#
# Save this to /etc/systemd/system/
# Run systemctl enable myapp-node-watcher.service && systemctl daemon-reload
#
[Unit]
Description=MyApp Server Watcher
#After=network.target
[Service]
Type=oneshot
ExecStart=/usr/bin/systemctl restart myapp-node
[Install]
WantedBy=multi-user.target
#########
# File: myapp-node.service
#
# Save this to /etc/systemd/system/
# Run systemctl enable myapp-node.service && systemctl daemon-reload && systemctl start myapp-node
#
[Unit]
Description=MyApp Server
[Service]
ExecStart=/usr/bin/node /home/myuser/myappdir/public_html/server.js
# Required on some systems
WorkingDirectory=/home/myuser/myappdir/public_html
Restart=always
# Restart service after 10 seconds if node service crashes
RestartSec=10
# Output to syslog
StandardOutput= /home/myuser/myappdir/logs/myapp.out.log
StandardError= /home/myuser/myappdir/logs/myapp.err.log
SyslogIdentifier=nodejs-myapp
User=myuser
Group=mygroup
# Define what port is supposed to have node listening. In this example we choosed 60000
Environment=NODE_ENV=production PORT=60000
[Install]
WantedBy=multi-user.target

To setup a node app as a systemd service and get it being reloaded each time you change code files use the following. This approach requires THREE files:

  • myapp-node.service (where your node server is started)
  • myapp-node-watcher.service (where your node server is restarted when changes in files are made)
  • myapp-node-watcher.path (that checks if any file is changed)

Change the name to something meaningful but keep in mind that the *-watcher.service and the *-watcher.path must have the same name

Do it all as root or, better, as superuser.

After this issue the command systemctl status myapp-node -l to check if myapp is running. Change a file on the directory defined at the last file wait a sec and do the last command again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment