How do I run a Node.js application as its own process?

Solution 1:

2016 answer: nearly every Linux distribution comes with systemd, which means forever, monit, PM2, etc. are no longer necessary - your OS already handles these tasks.

Make a myapp.service file (replacing 'myapp' with your app's name, obviously):

[Unit]
Description=My app

[Service]
ExecStart=/var/www/myapp/app.js
Restart=always
User=nobody
# Note Debian/Ubuntu uses 'nogroup', RHEL/Fedora uses 'nobody'
Group=nobody
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production
WorkingDirectory=/var/www/myapp

[Install]
WantedBy=multi-user.target

Note if you're new to Unix: /var/www/myapp/app.js should have #!/usr/bin/env node on the very first line and have the executable mode turned on chmod +x myapp.js.

Copy your service file into the /etc/systemd/system folder.

Tell systemd about the new service with systemctl daemon-reload.

Start it with systemctl start myapp.

Enable it to run on boot with systemctl enable myapp.

See logs with journalctl -u 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).

Solution 2:

Use Forever. It runs Node.js programs in separate processes and restarts them if any dies.

Usage:

  • forever start example.js to start a process.
  • forever list to see list of all processes started by forever
  • forever stop example.js to stop the process, or forever stop 0 to stop the process with index 0 (as shown by forever list).

Solution 3:

I've written about my deployment method here: Deploying node.js apps

In short:

  • Use git post-receive hook
  • Jake for the build tool
  • Upstart as a service wrapper for node
  • Monit to monitor and restart applications it they go down
  • nginx to route requests to different applications on the same server

Solution 4:

pm2 does the tricks.

Features are: Monitoring, hot code reload, built-in load balancer, automatic startup script, and resurrect/dump processes.

Solution 5:

You can use monit, forever, upstart or systemd to start your server.

You can use Varnish or HAProxy instead of Nginx (Nginx is known not to work with websockets).

As a quick and dirty solution you can use nohup node your_app.js & to prevent your app terminating with your server, but forever, monit and other proposed solutions are better.