叼花硬汉 2010-10-25 19:34 采纳率: 0%
浏览 825
已采纳

如何运行 node.js 作为后台服务的应用程序?

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, i.e.: 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:

转载于:https://stackoverflow.com/questions/4018154/how-do-i-run-a-node-js-app-as-a-background-service

  • 写回答

24条回答 默认 最新

  • 七度&光 2015-03-13 22:23
    关注

    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 Debian/Ubuntu uses 'nogroup', RHEL/Fedora uses 'nobody'
    Group=nogroup
    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

    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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(23条)

报告相同问题?

悬赏问题

  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波