Last Updated: February 25, 2016
·
3.617K
· stevelacy

Auto deploy node.js repos - git hooks

Easy method of deploying node.js applications from git pushes.

  • Stats

    repo name: codetip

    branch name: master

    server folder for repo: /var/www/codetip/

    webhook folder for repo: /var/www/codetip/hook/

Server

  1. Setup the git repo

$ git clone https://github.com/github-user/github-repo

  1. Create a hook.js file in the hook folder (/var/www/codetip/hook/hook.js)

hook/hook.js

var gith = require('gith').create(6000);  // run on port 6000
var exec = require('child_process').exec; 

gith({
  repo: 'stevelacy/codetip'  // the github-user/repo-name
}).on('all', function(payload){

    console.log("push received");
    exec('/var/www/codetip/hook/hook.sh ' + payload.branch, function(err, stdout, stderr){
      if (err) return err;
      console.log(stdout);
      console.log("git deployed to branch " + payload.branch);
    });
});
  1. Install the needed package:

    npm install gith

  2. Create hook.sh

hook/hook.sh

#!/bin/sh

git pull "origin" $1

return

Set the permissions:

$ chmod +x hook/hook.sh

Github.com

Add the git hook to your github repo.

https://developer.github.com/webhooks/creating/

Set the Payload URL to yourdomain.com:6000

Run the node script:

$ node hook/hook.js

Using forever or a similar launcher will keep the node process running when you close your terminal.

Any push to the repo should trigger the payload and call the hook.sh

Farther modifications include a deploy command to run once the git repo has pulled or fetched the new data.

1 Response
Add your response

There is a way to use this method with repo on Bitbucket?

over 1 year ago ·