~Onlooker 2010-10-25 19:34 采纳率: 0%
浏览 704
已采纳

如何运行 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

  • 写回答

25条回答 默认 最新

  • 乱世@小熊 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).

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

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测