Use Webhooks of GitHub/GitLab for automated website deployment

Source: Internet
Author: User
Tags php website webhook

Use Webhooks of GitHub/GitLab for automated website deployment

I have long wanted to write this topic. Today I have the opportunity to study the automated deployment of git. The final result is that whenever a new commit is pushed to the master branch, git pull is automatically pulled from the test/production server to obtain the latest code, it eliminates repetitive work for programmers to perform part-time O & M over ssh to pull code deployment. We also need Agile development, right? What is agile development, eXtreme Programming, fast iteration, continuous integration, lean startup, how is the slogan high-end? Finally, I wrote an automated script ......

I. automated deployment script

Make sure that the Web directory to be deployed is a repository cloned by git. In this way, rollback is also convenient, and you can simply checkout a previous version.

Write a shell

#!/bin/bash WEB_PATH='/var/www/'WEB_USER='lovelucydev'WEB_USERGROUP='lovelucydev' echo "Start deployment"cd $WEB_PATHecho "pulling source code..."git reset --hard origin/mastergit clean -fgit pullgit checkout masterecho "changing permissions..."chown -R $WEB_USER:$WEB_USERGROUP $WEB_PATHecho "Finished."

What we need to do below is to automatically call this script whenever there is a push.

2. Listening to Web Hooks

Both GitHub and GitLab support Webhooks settings.

Fill in the URL of the server to be deployed on the Payload URL, for example, Then, every time a push event occurs, GitHub will send a POST request to this address. Of course, you can also choose to send a POST notification to you for any event. GitHub also has a Secret setting, which is a string. If it is added, a Hash value will be included in the HTTP header of the POST request to verify the ciphertext, proving that the POST is actually from GitHub, otherwise, no one will POST to that address. You don't know who it is, do you ......

Then we need to write a script to accept POST requests in the Because I ran node on my machine, I found a nodejs middleware github-webhook-handler. If you want to deploy a PHP website, you should findThe best language in the worldPHP version, or write one by yourself, you only need to receive$_POSTWell, it's easy. It's not nonsense. Mdoda (• yunω • NLP)

$ npm install -g github-webhook-handler

In view of the slow speed of npm repo pulling on domestic servers, we can use Alibaba's image, which is said to be synchronized with the official website once every 10 minutes. _ (: 3 "rows )_

$ npm install -g cnpm --registry=$ cnpm install -g github-webhook-handler

Okay, everything is ready. below is the NodeJS listener.deploy.js

Var http = require ('http') var createHandler = require ('github-webhook-handler') var handler = createHandler ({path: '/incoming', secret: 'myhashsecret'}) // The above secret must be consistent with the function run_cmd (cmd, args, callback) {var spawn = require ('child _ Process') set in the GitHub background '). spawn; var child = spawn (cmd, args); var resp = ""; child. stdout. on ('data', function (buffer) {resp + = buffer. toString () ;}); child. stdout. on ('end', function () {callback (resp)});} http. createServer (function (req, res) {handler (req, res, function (err) {res. statusCode = 404 res. end ('no such location ')})}). listen (7777) handler. on ('error', function (err) {console. error ('error: ', err. message)}) handler. on ('push', function (event) {console. log ('Received a push event for % s to % s', event. payload. repository. name, event. payload. ref); run_cmd ('sh ',['. / '], function (text) {console. log (text)});})/* handler. on ('issues', function (event) {console. log ('stored an issue event for % action = % s: # % d % s', event. payload. repository. name, event. payload. action, event. payload. issue. number, event. payload. issue. title )})*/

So you can run it directly.

$ nodejs deploy.js

Of course, to prevent NodeJS from being suspended, we can enable the process management service forever, which is similar to the supervisor in python.

$ cnpm install -g forever$ forever start deploy.js

In this way, even if the node. JS Code fails in an error somewhere, it will automatically restart a process to ensure that the service is still available. Several forever commands are quite simple.

$ forever list$ forever stop 1$ forever restartall

The above NodeJS runs the Web service on port 7777. We can use Nginx to reverse proxy to port 80 (optional)

server {    listen 80;    server_name;    # ...    location / {        # ...    }    location /incoming$ {        proxy_pass;    }}
3. integrate third-party services

Did you notice that there is a Service tab in the GitHub project background?

This is a large number of third-party services officially integrated by GitHub. It is a bit similar to the IFTTT pace and can do a lot of things. For example, if someone pushes the code, I will send a notification to our hipchat chat group. If someone mentions issue, it will automatically send a welcome email to him ......

GitLab also has these features. For more details, go and study them ~


GitHub Tutorials:

Create a personal technical blog via GitHub

GitHub tutorials

Git tag management details

Git branch management

Git remote repository details

Git local Repository (Repository) Details

Git server setup and Client installation

Git Overview

Share practical GitHub tutorials

GitHub details: click here
GitHub: click here

This article permanently updates the link address:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.