【问题标题】:Ansible hangs when starting node.js server启动 node.js 服务器时 Ansible 挂起
【发布时间】:2014-01-04 09:30:50
【问题描述】:

我想在 ansible playbook 中启动我的 node.js 应用程序。现在,最终指令如下所示:

  - name: start node server
    shell: chdir=${app_path} npm start&

问题是 ansible 永远不会从这里返回。我怎样才能让它继续?

【问题讨论】:

标签: node.js ansible


【解决方案1】:

Forever 似乎是启动和守护 Node.js 应用程序的最简单和最简单的方法。目前,没有永久的 Ansible 模块,但您仍然可以使用以下方式永久安装并运行您的应用:

- name: "Install forever (to run Node.js app)."
  npm: name=forever global=yes state=present

- name: "Check list of Node.js apps running."
  command: forever list
  register: forever_list
  changed_when: false

- name: "Start example Node.js app."
  command: forever start /path/to/app.js
  when: "forever_list.stdout.find('/path/to/app.js') == -1"

这是完全幂等的,非常适合我。你可以为 Ansible 编写一个小的 forever 模块来为你做这些事情(比如 service 模块),但现在这工作。

我在 Server Check.in 的博客上有一个如何start a Node.js app with Forever and Ansible 的完整示例。

【讨论】:

  • 感谢您的解决方案。但这仅用于运行应用程序一次。如果您想再次重新部署它怎么办?请在下面查看我的答案以获得小的改进。
  • @QuyenNguyenTuan 很简单,在forever_list.stdout.find('/path/to/app.js') != -1时使用forever restart /path/to/app.js
  • 不错的解决方案,我发现这些任务安装forever 没有任何问题,但无法运行我的节点脚本。如果我手动运行forever start /home/vargrant/project/socket.js,我可以启动我的socket.js 脚本,但如果我将它用作ansible command 的一部分,它不会启动脚本。有什么想法吗?
  • 解决了我在这里描述的问题。我没有意识到forever 会根据用户列出正在运行的程序。基本上,我正在使用 Ansible 成为 Root,然后我正在检查我的普通流浪用户,因此它没有显示节点脚本实际上正在运行。
  • 请注意,Ansible 2.x 上的 npm 模块中有一个错误(至少在此评论中如此),该错误会阻止使用 state=latest 进行安装。请改用presentgithub.com/ansible/ansible-modules-extras/issues/137
【解决方案2】:

使用 Forever 是在后台运行 nodejs 应用程序的最佳解决方案。 @geerlingguy 的解决方案非常适合运行一次应用,但是如果你想重新部署应用,你必须先停止服务器,然后重新启动它:

- name: Get app process id
  shell: "ps aux | grep app.js | grep -v grep | awk '{print $2}'"
  register: process_id

- name: Stop app process
  shell: kill -9 {{ item }}
  with_items: process_id.stdout_lines
  ignore_errors: True  # Ignore error when no process running

- name: Start application
  command: forever start path/to/app.js
  environment:
    NODE_ENV: production  # Use this if you want to deploy the app in production

【讨论】:

  • 您也可以使用forever restart,或forever restartall 来节省一些步骤。
【解决方案3】:

尝试使用 nohup:

- name: start node server
  shell: chdir=${app_path} nohup npm start &

不过,更好的方法可能是尝试使用forever,这样如果应用终止,它会自动重启。

【讨论】:

    【解决方案4】:

    当您关闭 shell 时,进程会收到 SIGHUP 信号(如 kill -1)。 您可以在 app.js 文件中捕获信号“SIGHUP”。

    process.on('SIGHUP', function() {
                logger.info("SIGHUP signal was interrupted");
            });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-25
      • 1970-01-01
      • 2021-05-09
      • 1970-01-01
      • 2019-04-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多