Webhook 实践 —— 用nodo搭建git自动部署
2017-08-14
git
使用Webhook ,用node搭建git自动化部署
依赖 http和exec 两个中间件
commands 数组中是linux服务器执行的命令 监听一个端口
具体代码如下
const http = require('http')
const exec = require('exec')
const PORT = 3389
const PATH = '../blogline'
var deployServer = http.createServer(function(request, response) {
if (request.url.search(/pull\/?$/i) > 0) {
var commands = [
'cd ' + PATH,
'git pull'
].join(' && ')
exec(commands, function(err, out, code) {
if (err instanceof Error) {
response.writeHead(500)
response.end('Server Internal Error.')
throw err
}
process.stderr.write(err)
process.stdout.write(out)
response.writeHead(200)
response.end('Deploy Done.')
})
} else {
response.writeHead(404)
response.end('Not Found.')
}
})
deployServer.listen(PORT)
启动PM2守护进程(PM2是node的进程守护管理)
PM2 start pull.js (pull.js为上述代码的js文件名)
配置 Webhook
以码云为例: 在项目管理中找到webhooks 输入你服务器地址,例如 http://www.example.com:3389/pull (需要带着你的端口号,后面的pull为你的接口)
pull接口在你的代码http.createServer里的这一段 request.url.search(/pull\/?$/i) > 0
此时你请求此接口 ,服务器就会触发一次 git pull 操作
若遇到服务器需要输入密码,则需配置git的ssh,可以设置为默认不输入密码,具体可以看我其他文章。