Github托管项目实现自动化部署

当咱们利用github来托管项目时,每次部署项目都要走一样的流程,敲击一样的命令行,尤为的咱们的node项目更是没法忍受这种重复工做。html

那到底有没有一种能够解放咱们双手,当咱们提交代码后,服务器自动执行咱们已经制定好的命令行,答案是咱们能够利用Github自有的Webhooksnode

Webhooks

Webhooks是来监测你在github上的各类事件,咱们能够经过定制它来监测一个push事件,每当咱们提交代码时Webhooks会被触发,这是咱们能够经过配置一个HOST POST请求到你所须要的地址。nginx

如何配置

找到你在Github上的项目地址上的SettingWebhooks,以下图配置:git

图片描述

项目配置

  • 编写执行shell命令

在项目根目录下新建deployed.sh文件,输入你想在服务器上执行的命令行,如:github

cd /front/docs/

git pull origin master
  • 编写执行脚本

在项目根目录下新建deployed.js文件web

var http = require('http')
var spawn = require('child_process').spawn
var createHandler = require('github-webhook-handler')
var handler = createHandler({
  path: '/pushCode',
  secret: '12345678'
})
http.createServer(function (req, res) {
  handler(req, res, function (err) {
    res.statusCode = 404;
    res.end('no such location')
  })
}).listen(3000)

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)
  rumCommand('sh', ['./deployed.sh'], function (txt) {
    console.log(txt)
  })
})

function rumCommand(cmd, args, callback) {
  var child = spawn(cmd, args)
  var response = ''
  child.stdout.on('data', function (buffer) {
    response += buffer.toString()
  })
  child.stdout.on('end', function () {
    callback(response)
  })
}

nginx配置

执行脚本跑在了3000端口,咱们服务器对应启用到 3000 端口shell

upstream test {
    server 127.0.0.1:3000;
}

server {

  location /pushCode {
    proxy_pass http://test;
    proxy_redirect off;
  }

}

部署项目

首次部署到服务器时,仍然是须要咱们手动执行命令git pull项目,当咱们在服务器上clone下咱们的项目后,在本地尝试修改下代码,而后再次提交,可看到后台的日志json

图片描述

再次查看Webhooks服务器

图片描述

表示已经自动触发了接口,项目自动化部署成功。ui

管理应用

在服务器上执行node命令后,当咱们离开服务器后,实际上程序进程关闭了,因此咱们利用pm2来管理咱们的node进程。

在项目根目录下新建pm2.json

[{
  "name": "test",
  "script": "deployed.js",
  "env_dev": {
    "NODE_ENV": "development"
  },
  "env_production": {
    "NODE_ENV": "production"
  }
}]

把全部的代码推送上服务器,进入服务器项目目录,执行

// 启动命令
pm2 start pm2.json

// 查看是否启动
pm2 list

// 查看日志
pm2 logs

本文感谢SkyCai提供的思路。原文地址

相关文章
相关标签/搜索