使用Github Action部署Docker映像

时间:2020-10-31 21:14:11

标签: docker github github-actions

我有一个Github Action,它用于标记,构建和部署docker映像。 当有拉取请求时,我将使用以下文件进行构建工作:# This is a basic workflow to help you get started with Actions name: Build # Controls when the action will run. Triggers the workflow on push or pull request # events but only for the master branch on: pull_request: branches: [ master ] # A workflow run is made up of one or more jobs that can run sequentially or in parallel jobs: docker: # The type of runner that the job will run on runs-on: ubuntu-latest env: DOCKERHUB_REPOSITORY: ${{ secrets.DOCKERHUB_REPOSITORY }} # Steps represent a sequence of tasks that will be executed as part of the job steps: # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it - uses: actions/checkout@v2 - name: docker build run: | # Tag the image with the commit hash docker build -t $DOCKERHUB_REPOSITORY . docker tag $DOCKERHUB_REPOSITORY:latest $DOCKERHUB_REPOSITORY:$(git log -1 --pretty=%h)

deploy.yml

对于部署,我必须使用以下文件进行构建和部署:# This is a basic workflow to help you get started with Actions name: Deploy # Controls when the action will run. Triggers the workflow on push or pull request # events but only for the master branch on: push: branches: [ master ] # A workflow run is made up of one or more jobs that can run sequentially or in parallel jobs: docker: # The type of runner that the job will run on runs-on: ubuntu-latest env: DOCKERHUB_REPOSITORY: ${{ secrets.DOCKERHUB_REPOSITORY }} # Steps represent a sequence of tasks that will be executed as part of the job steps: # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it - uses: actions/checkout@v2 - name: docker login env: DOCKERHUB_USER: ${{ secrets.DOCKERHUB_USER }} DOCKERHUB_ACCESS_TOKEN: ${{ secrets.DOCKERHUB_ACCESS_TOKEN }} run: | docker login -u $DOCKERHUB_USER -p $DOCKERHUB_ACCESS_TOKEN - name: docker build run: | # Tag the image with the commit hash docker build -t $DOCKERHUB_REPOSITORY . docker tag $DOCKERHUB_REPOSITORY:latest $DOCKERHUB_REPOSITORY:$(git log -1 --pretty=%h) - name: docker push run: | docker push $DOCKERHUB_REPOSITORY

Example

对我来说,build部分是重复的,但是我没有发现如何在不同文件的作业中使用依赖项。它不起作用。

我如何告诉github动作,deploy部分取决于build ?,带有2个不同的文件。

链接:https://docs.github.com/en/free-pro-team@latest/actions/learn-github-actions/managing-complex-workflows#creating-dependent-jobs

1 个答案:

答案 0 :(得分:1)

您可以将它们合并到一个CI / CD管道中。这应该同时由主服务器中的pushpull_request触发。这有几个优点;

  • 如果构建失败,管道将自动中止
    (可以肯定的是,您可以添加if: ${{ success() }}
  • 没有重复的步骤,docker build仅定义一次。
  • 仍然只能通过使用 conditions pushpull_request上执行步骤:
if: ${{ github.event_name == 'push' }} // OR
if: ${{ github.event_name == 'pull_request' }}
  • 更少的管道需要维护!