Running Node.js App with Supervisord on Homestead
Earlier I covered how to continuously run Node.js app with Forever. In this article I will explain how to run Node.js app with Supervisord. Since Homestead already has Supervisord installed, we will use it. First, let’s create a simple node application. Edit after.sh script in Homestead installation to contain the following code:
#!/bin/sh
cd /var/www
sudo mkdir node-web-server
sudo chown vagrant:vagrant node-web-server
sudo chmod 770 node-web-server
sudo chmod g+s node-web-server
cd node-web-server
npm init -y
npm install express --save
cat > server.js << EOF1
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send('Hello Express!');
});
app.listen(3000, function(){
console.log('Server is listening on port 3000');
});
EOF1
Next, let's create a proxy nginx path to port 3000 in Homestead.yaml file.
- map: node-app.dev
to: 3000
type: proxy
Don't forget to add node-app.dev record to your hosts file.
Now lets reload our homestead vm instance with vagrant reload --provision
After the instance is up and running let's create and /etc/supervisor/conf.d/nodeserver.conf with the following content.
[program:nodeserver]
command=/usr/bin/node /var/www/node-web-server/server.js
directory=/var/www/node-web-server
autostart=true
autorestart=true
startretries=3
user=vagrant
From command line run
sudo supervisorctl reread
sudo supervisorctl update
to update Supervisord. When all set and done you should be able to go to node-app.dev and see you application. If the you restart the server, or node process gets stopped or killed, Supervisord will restart it back.