~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条)

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来