Didn"t forge 2010-10-25 19:34 采纳率: 25%
浏览 737
已采纳

如何运行 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 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号