node.js - 如何基于 GitHub webhook 自动化部署 docker?

标签 node.js linux git docker continuous-integration

所以我继承了一个应用程序,并且对当前的部署工作流程不太满意。有一个运行在 ec2 服务器上的 docker 实例,开发人员一直在像这样 merge 他们的本地工作:

rsync -arhvz --progress ./ ubuntu@52.12.345.67:/home/ubuntu/app --exclude node_modules

然后进入服务器本身并运行 deploy.sh 脚本。我只想向 master 分支发送一个 push 事件来触发同步和部署。这怎么可能?据我所知,我们不为 Docker hub 帐户付费 - 我们没有私有(private) docker 注册表。

最佳答案

一些解决方案:

  • 使用 git pre-push hook将在每次本地推送到远程之前执行脚本的脚本
  • 在你的服务器上创建一个裸 git 仓库,将你的更改推送到这个 git 远程并使用 post-receive hook 检查最后的更改。
  • 使用 Github webhook 跟踪 Github 上的推送事件,您需要让您的服务器监听一个端口以接收 webhook 事件

预推钩子(Hook)

在您的本地存储库中,编辑/创建 .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 部署到它

您可以在您的服务器上创建一个裸 git 存储库,并创建一个 post-receive Hook 脚本,该脚本将使用 git 来检查您的服务器存储库。来自 this guide :

#!/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

请注意,此解决方案仅使用 git

Github 网络钩子(Hook)

您可以使用这个 docker-hook项目,它是一个 Python 服务器,用于监听 webhook uri 上的 POST。它最初用于 Docker Hub webhook,但也适用于 Github webhook(尽管不解析事件)。

网络钩子(Hook)

在你的服务器上:

  • 下载 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
  • 使用 token 启动它(例如使用 uuidgen 生成):
docker-hook -t 3ea4e9d8-8fff-47e5-a704-65ab21de6963 -c /path/to/deploy.sh

在 Github 中,转到您的 repo 设置,使用 token 作为路径创建 webhook:

enter image description here

检查 webhook 是否正常工作(在 Recent Deliveries 选项卡中)

部署 key

现在,因为你想在你的服务器上触发一个git pull,你需要生成一个Deploy Key。这是用于部署(只读)的 ssh key ,您将需要在服务器端:

  • 如果尚未安装 git,请安装
  • 生成 key
  • 将此 key 复制到您的 repo/settings/Deploy key 选项卡

参见 this post一个完整的教程

enter image description here

现在您需要编辑您的 deploy.sh 脚本以执行 git pull 或新的 git clone 到您选择的位置

关于node.js - 如何基于 GitHub webhook 自动化部署 docker?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44864419/

相关文章:

git - 使用 Git 撤消临时更改

php - Raspberry Node.js 和执行命令

javascript - Nodejs 从请求中获取 [object Object]

javascript - 使用 mongoose 在 mongodb 中查找用户,并将结果返回为 JSON

linux - 在 linux 中分配静态 ip

git - 为 Git Flow 构建配置

git - 有没有办法在一个命令中获取 git 根目录?

node.js - 没有 Express 的 Node 中间件

linux - 如何使用 shellscript 解析 XML?

linux - 本地灯服务器的权限