13

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sangaloma
  • 392
  • 1
  • 3
  • 12

1 Answers1

41

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Christopher Francisco
  • 15,672
  • 28
  • 94
  • 206