本文介绍两种利用 Github Actions 生成 Docker 镜像的方法。

在 DockerHub

这个镜像会生成在https://hub.docker.com ,这是大多数的选择。

注意点​:

  • 需要项目仓库的 Secrets - Actions 中,新建两个变量 DOCKERHUB_USERNAME​、​DOCKERHUB_PASSWORD​,其值分别是 DockerHub 的用户名和密码;
  • DockerHub 不会自动使用 Github 的 README,如果需要显示它,要额外增加一个 Action。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
name: Build and Push Docker Image

on:
  push:
    branches:
      - master

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v3

      - name: Login to Docker Hub
        uses: docker/login-action@v2
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_PASSWORD }}

      - name: Build and Push Docker Image
        uses: docker/build-push-action@v4
        with:
          context: .
          push: true
          tags: Username/Imagename:latest

      - name: Docker Hub Description
        uses: peter-evans/dockerhub-description@v3
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_PASSWORD }}
          repository: Username/Imagename

在 Github

这个镜像会生成在https://ghcr.io ,可以通过 GitHub 项目的 Packages 访问,与 GitHub 的关联会更紧密,比如能自动使用 GitHub 的 README,以及版本管理功能。

注意点​:

  • 需要在项目仓库的 Settings - Actions - General 中,打开 Read adnd write permission​。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
name: Build and Push Docker Image

on:
  push:
    branches:
      - master

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v3

      - name: Login to Docker Hub
        uses: docker/login-action@v2
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Build and Push Docker Image
        uses: docker/build-push-action@v4
        with:
          context: .
          push: true
          tags: ghcr.io/Username/Imagename:latest