Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to run a Node.js script as service in Ubuntu?

Tags:

node.js

ubuntu

I have a Node.js script that keeps my MongoDB database and the CRM database synced in real-time.

I want to run this script as a background task on my Ubuntu server. I found this solution, but it doesn't work for me. Is there another approach to reach this?

like image 614
sangaloma Avatar asked May 22 '18 16:05

sangaloma


People also ask

How do I run a node js service?

The usual way to run a Node. js program is to run the globally available node command (once you install Node. js) and pass the name of the file you want to execute. While running the command, make sure you are in the same directory which contains the app.

How do I start node service in Linux?

Start it with systemctl start myapp . Enable it to run on boot with systemctl enable myapp . This is taken from How we deploy node apps on Linux, 2018 edition, which also includes commands to generate an AWS/DigitalOcean/Azure CloudConfig to build Linux/node servers (including the . service file).


1 Answers

If you just want to start your application, you could use Forever or PM2 for running and auto-restarting on crash. However, this is not a background task.

For a background task that starts on server reboot, the post you linked is the right way to go. If it didn't work, maybe this article will help you. This is from official Express site: Process managers for Express apps

Basically, you create

[Unit]
Description="My Express App"

[Service]
ExecStart=/usr/bin/node server.js
WorkingDirectory=/project/absolute/path
Restart=always
RestartSec=10
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=MyApp
Environment=NODE_ENV=production PORT=8080

[Install]
WantedBy=multi-user.target

Into a /etc/systemd/system/my-app.service file and then use systemctl to start it:

systemctl enable my-app.service
systemctl start my-app.service

Now this assumes your Linux distribution works with systemctl. If your Linux distribution works with upstart or something else, then you need to google up the instruction for that process manager.

like image 144
Christopher Francisco Avatar answered Nov 08 '22 23:11

Christopher Francisco