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 Check.in 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.
Comments
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?same here! when I do a ps aux | grep node I see it starting, but after a couple of seconds it stops...
Very useful thanks, I used a lot of your ideas.
Only difference is that I use npm start to kick off forever (that way anyone with no knowledge can start your server, npm start everytime, every project, everywhere)
also the npm install ..
- name: Ensure node modules are installed
command: npm i
args:
chdir: ~/certs-server
creates: ~/certs-server/node_modules/express/package.json
much thx
Hello - I'm trying to start apps using forever using your method. However, i'm unable to start it. I'm using Vagrant to test the playbook.
My guess is that vagrant user is trying to start forever, instead of root user. But as you can see below, I have tried to change as root user but its not working.
- name: "Check list of Node.js apps running."
command: '/root/.nvm/v0.10.46/bin/forever list'
register: forever_list
changed_when: false
become: true
become_user: root
- name: Start node-app
command: '/root/.nvm/v0.10.46/bin/forever start --uid "agent" /node-directory/app.js'
when: "forever_list.stdout.find('/node-directory/app.js') == -1"
become: true
become_user: root
Any suggestions?
The best advice would be to look at the example from Ansible for DevOps: https://github.com/geerlingguy/ansible-for-devops/blob/master/nodejs/provisioning/playbook.yml#L28-L47