使用github action自动构建镜像——合成大西瓜

2021-02-09  本文已影响0人  惜鸟
image

合成大西瓜项目地址:https://github.com/liyupi/daxigua

概述

最近看到一个叫做合成大西瓜的小游戏挺不错的,所以打算自己部署一下玩一玩。由于本人比较喜欢用docker部署项目,项目中有提供Dockerfile用来构建镜像,这里记录一下使用github action实现提交代码后自动构建镜像并推送镜像到阿里云仓库

游戏效果图

github action自动构建步骤

github actions 推送docker镜像官方文档:https://docs.github.com/cn/actions/guides/publishing-docker-images

1、从源仓库中fork项目到自己的仓库

image

2、点击Actions创建workflows

关于GitHub action的工作流程语法可以查看官方文档:https://docs.github.com/cn/actions/reference/workflow-syntax-for-github-actions

image
创建一个自己的workflow
image
.github/workflows/目录下创建一个docker-push.yml文件,文件内容如下:
# This is a basic workflow to help you get started with Actions

name: CI

# Controls when the action will run. 
# 控制这个action什么时候运行
on:
  # Triggers the workflow on push or pull request events but only for the master branch
  # 这里是只有master分支发生 push 或者 pull事件时才会触发action运行
  push:
    branches: [ master ]
  pull_request:
    branches: [ master ]

  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch: 

# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
  # This workflow contains a single job called "build"
  build:
    # The type of runner that the job will run on
    runs-on: ubuntu-latest

    # 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: Build And Push Docker image
        env:
          # 指定自己的仓库地址
          docker_repo: registry.cn-shenzhen.aliyuncs.com/devan
          # 指定镜像名称
          image_name: daxigua
          # 指定镜像标签
          tag: latest
        run: | 
          # 查看docker 版本
          docker version
          # 登录阿里云镜像仓库, 这里登录docker的用户名和密码在Secrets中设置,下面有介绍
          docker login --username=${{ secrets.DOCKER_USERNAME }} --password=${{ secrets.DOCKER_PASSWORD }} registry.cn-shenzhen.aliyuncs.com
          # 使用Dockerfile构建镜像
          docker build . --file Dockerfile --tag $docker_repo/$image_name:$tag
          # 推送镜像到镜像仓库
          docker push $docker_repo/$image_name:$tag


image
这里保存提交之后会触发action构建,由于文件中的${{ secrets.DOCKER_USERNAME }}${{ secrets.DOCKER_USERNAME }}没有设置,会导致构建失败,查看构建日志我们会发现提示docker没有登录,下面我们需要设置docker登录的用户名和密码。

3、在Secrets中设置登录docker的用户名和密码

上面环境变量中应用的${{ secrets.DOCKER_USERNAME }}${{ secrets.DOCKER_USERNAME }}就是在下面设置的:

image

4、我们修改代码提交后,会再次触发action构建

可以看到整个构建流程


image

我这里推送的镜像如下:

registry.cn-shenzhen.aliyuncs.com/devan/daxigua:latest

使用如下命令启动容器:

docker run --name daxigua -d -p 5000:5000 registry.cn-shenzhen.aliyuncs.com/devan/daxigua:latest

启动容器之后访问:http://localhost:5000 即可愉快的玩游戏了

上一篇 下一篇

猜你喜欢

热点阅读