How do I run a node.js app as a background service?

Since this post has gotten a lot of attention over the years, I've listed the top solutions per platform at the bottom of this post.


Original post :

I want my node.js server to run in the background, ie: when I close my terminal I want my server to keep running. I've googled this and came up with this tutorial, however it doesn't work as intended. So instead of using that daemon script, I thought I just used the output redirection (the 2>&1 >> file part), but this too does not exit - I get a blank line in my terminal, like it's waiting for output/errors.

I've also tried to put the process in the background, but as soon as I close my terminal the process is killed as well.

So how can I leave it running when I shut down my local computer?


Top solutions :

  • Systemd (Linux)
  • Launchd (Mac)
  • node-windows (Windows)
  • PM2 (Node.js)

  • Copying my own answer from How do I run a Node.js application as its own process?

    2015 answer : nearly every Linux distro comes with systemd, which means forever, monit, 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 RHEL/Fedora uses 'nobody', Debian/Ubuntu uses 'nogroup'
    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.

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

    Start it with systemctl start myapp .

    Enable it to run on boot with systemctl enable myapp .

    See logs with journalctl -u myapp

    More details at: How we deploy node apps on Linux, 2018 edition


    您可以使用Forever,一个简单的CLI工具来确保给定节点脚本连续运行(即永远):https://www.npmjs.org/package/forever


    UPDATE - As mentioned in one of the answers below, PM2 has some really nice functionality missing from forever. Consider using it.

    Original Answer

    Use nohup:

    nohup node server.js &
    

    EDIT I wanted to add that the accepted answer is really the way to go. I'm using forever on instances that need to stay up. I like to do npm install -g forever so it's in the node path and then just do forever start server.js

    链接地址: http://www.djcxy.com/p/48470.html

    上一篇: Node.js最佳实践异常处理

    下一篇: 如何将node.js应用程序作为后台服务运行?