如何基于GitHub webhook自动化Docker部署?
所以我inheritance了一个应用程序,并不太满意当前的部署工作stream程。 有一个在ec2服务器上运行的docker实例,开发人员一直在合并他们的本地工作:
rsync -arhvz --progress ./ ubuntu@52.12.345.67:/home/ubuntu/app --exclude node_modules
然后进入服务器本身并运行一个deploy.sh
脚本。 我只是喜欢push
事件到主分支触发这个同步和部署。 这怎么可能? 据我所知,我们不支付docker中心帐户 – 我们没有私人dockerregistry。
一些解决scheme
- 使用一个git pre-push hook脚本,在每次本地推送到远程之前执行该脚本
- 在你的服务器上创build一个纯粹的git仓库,把你的更改推送到这个git远程,并使用post-receive钩子检出最后一个更改
- 使用Github webhook跟踪Github上的推送事件,您将需要让服务器监听端口以接收webhook事件
预推钩
在本地存储库中,编辑/创build.git/hooks/pre-push
文件:
#!/bin/bash rsync -arhvz --progress ./ ubuntu@52.12.345.67:/home/ubuntu/app --exclude node_modules ssh ubuntu@52.12.345.67 "/home/ubuntu/deploy.sh"
这样,您的修改将在每次本地推送到远程之前同步。 deploy.sh
也被触发
在你的服务器上设置一个git仓库,并使用git进行部署
你可以在你的服务器上创build一个纯粹的git仓库,并创build一个post-receive
钩子脚本,它将使用git
来签出你的服务器仓库。 从这个指南 :
#!/bin/bash while read oldrev newrev ref do # only checking out the master (or whatever branch you would like to deploy) if [[ $ref =~ .*/master$ ]]; then echo "Master ref received. Deploying master branch to production..." git --work-tree=/home/ubuntu/app/deploy-folder/ --git-dir=/home/ubuntu/app/project.git/ checkout -f else echo "Ref $ref successfully received. Doing nothing: only the master branch may be deployed on this server." fi done
请注意,这个解决scheme只使用git
Github Webhook
你可以使用这个docker-hook项目,这是一个Python服务器监听你的webhook上的POST
。 它最初用于Docker Hub webhook,但也适用于Github webhook(尽pipe不parsing事件)。
networking挂接
在你的服务器上:
- 下载docker-hook python脚本
curl https://raw.githubusercontent.com/schickling/docker-hook/master/docker-hook > /usr/local/bin/docker-hook; chmod +x /usr/local/bin/docker-hook
- 用一个令牌来启动它(例如用
uuidgen
生成):
docker-hook -t 3ea4e9d8-8fff-47e5-a704-65ab21de6963 -c /path/to/deploy.sh
在Github中,转到您的回购设置,创build带有令牌的webhook作为path:
检查webhook是否正常工作(在最近交付标签中)
部署密钥
现在,当你想触发你的服务器上的git pull
,你将需要生成一个部署密钥 ,这是一个ssh密钥用于部署(只读),您将需要,在服务器端:
- 如果尚未安装,请安装
git
- 生成一个密钥
- 复制此密钥在您的回购/设置/部署密钥选项卡
看到这个职位的完整教程
现在,您需要编辑您的deploy.sh
脚本来执行git pull
或新的git clone
到您select的位置