logo头像
Snippet 博客主题

通过webHooks 实现热部署

本文于930天之前发表,文中内容可能已经过时。

原理

  • 配置好github上的webhooks后,每次在本地执行git push到github上的时候,github会自动发送一个post请求到服务器,
  • 服务器上接收到这个信号,执行写好的shell脚本,shell脚本的内容第一步cd到目标目录,然后执行git pull / npm install等操作
  • 因为要在服务器上执行一系列git命令,所以需要在服务器上事先生成密钥,将公钥放到github上

具体步骤

配置webHook

  • 在github上新建一个仓库,选择setting –> 选择webhooks –> add webhook –> 配置好github上的webhooks
    第一步

第二步

第三步

第四步

接收github的请求(写在服务器端, 需要安装github-webhook-handler模块)

  • 第一步:编写监听端口,监听后执行第二步中的shell

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    var http = require('http')
    var createHandler = require('github-webhook-handler')
    // secret 保持和 GitHub 后台设置的一致
    var handler = createHandler({ path: '/', secret: 'wechat' })
    function run_cmd(cmd, args, callback) {
    var spawn = require('child_process').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', ['./deploy.sh',event.payload.repository.name], function(text){ console.log(text) });
    })
  • 第二步:在同级目录下编写shell脚本,命名为deploy.sh

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    #!/bin/bash
    WEB_PATH='/root/zyj/'$1 //你要pull到服务器的的地址 $1 就是你github的仓库名称
    WEB_USER='root'
    WEB_USERGROUP='root'
    echo "Start deployment"
    echo $1
    cd $WEB_PATH
    echo "pulling source code..."
    git reset --hard origin/master
    git clean -f
    git pull origin master
    npm install
    git checkout master
    echo "changing permissions..."
    chown -R $WEB_USER:$WEB_USERGROUP $WEB_PATH
    echo "Finished."

在服务器上生成密钥,并在相应pull目录和github仓库建立联系

  • 服务器上安装git

    1
    yum install git
  • 生成git密钥

    1
    ssh-keygen -t raa -C ‘邮箱地址’ -f ~/.ssh/id_rsa
  • 将公钥放在github上

    1
    2
    // 找到.pub文件
    cd ~/.ssh
  • 测试ssh

    1
    2
    // 出现Permission denied(publickey)执行下一步
    ssh -T git@second.github.com
1
2
ssh-add ~/.ssh/id_rsa
// 再次执行ssh -T git@second.github.com
  • 到相应目录下关联github,保证在该目录下能够git pull成功
    1
    2
    3
    cd /root/zyj/demo
    git init
    git remote add origin git@github.com:账号/仓库名.git

最后执行node

1
pm2 start index.js --name webhook-test --watch

参考链接