Start a Node.js app with Forever and Ansible

Forever is a really simple and flexible tool to daemonize Node.js apps. Instead of running them with nohup node /path/to/app.js &, run them with forever (so you can forever start [app] and forever stop [app], among other things). Server uses Ansible to deploy our Node.js apps, and there's currently no Ansible module to control forever like you control service, but you can still use the following plays to install forever and run your app:

    - 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"

This is completely idempotent, and works great for us. You could program a little forever module for Ansible to do this stuff for you (like the service module), but this works well enough for our purposes.

Using Forever to run Node.js apps is also covered in Ansible for DevOps, in an example playbook that deploys and configures a Node.js app server.

This topic was also posted to Stack Overflow in this answer.


Nice solution, I have found that these tasks install forever without any problems but are unable for run my node script. If i manually run forever start /home/vargrant/project/socket.js I am able to start my socket.js script, but if i use this as part of an ansible command it does not start the script. Any ideas?