In a test or development environment we can start a node.js application with npm start . But this is not, what we want to do in production.
We need to start the application as soon as the server is up and running.
Here is a quick and easy way to achieve this goal.
Create a new file in /etc/systemd/system ( domino-db.service for example )
[Unit]
Description=domino-node-list sample
[Service]
ExecStart=/git/domino-node-list/app.js
Restart=always
User=root
Group=root
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production
WorkingDirectory=/git/domino-node-list/
[Install]
WantedBy=multi-user.target
Modify ExecStart and WorkingDirectory to point to the correct path in your installation.
Save domino-db.service and set execution rights to 744.
Check app.js for proper execution right (744).
Edit app.js and add
#!/usr/bin/env node
as the first line in the code.
Enable the service
systemctl enable domino-db
Created symlink from /etc/systemd/system/multi-user.target.wants/domino-db.service to /etc/systemd/system/domino-db.service.
Check with
systemctl status domino-db
● domino-db.service - domino-node-list sample
Loaded: loaded (/etc/systemd/system/domino-db.service; enabled; vendor preset: disabled)
Active: active (running) since Sun 2018-12-30 10:24:04 CET; 4min 15s ago
Main PID: 7163 (node)
Tasks: 7
CGroup: /system.slice/domino-db.service
└─7163 node /git/domino-node-list/app.js
Dec 30 10:24:04 serv02.fritz.box systemd[1]: Started domino-node-list sample.
Dec 30 10:24:04 serv02.fritz.box systemd[1]: Starting domino-node-list sample...
Dec 30 10:24:05 serv02.fritz.box app.js[7163]: Example app listening at http://:::3000
You can now start and stop the service at any time using
systemctl start domino-db
systemctl stop domino-db
Another option to start Node scripts at startup is using pm2 – a Node process manager. You can add several scripts, enable and disable them and over all you can set pm2 as a service at startup. Very neat, no scripting and systemd needed.