GitHub Actions 中的命名上下文
目录
您可以定义额外的构建上下文,并在 Dockerfile 中使用 FROM name 或 --from=name 访问它们。当 Dockerfile 定义了同名阶段时,它将被覆盖。
这在 GitHub Actions 中非常有用,可以重用其他构建的结果或将镜像固定到工作流中的特定标签。
将镜像固定到标签
用固定标签替换 alpine:latest
# syntax=docker/dockerfile:1
FROM alpine
RUN echo "Hello World"name: ci
on:
push:
jobs:
docker:
runs-on: ubuntu-latest
steps:
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Build
uses: docker/build-push-action@v6
with:
build-contexts: |
alpine=docker-image://alpine:3.21
tags: myimage:latest在后续步骤中使用镜像
默认情况下,Docker Setup Buildx action 使用 docker-container 作为构建驱动程序,因此构建的 Docker 镜像不会自动加载。
使用命名上下文可以重用构建的镜像
# syntax=docker/dockerfile:1
FROM alpine
RUN echo "Hello World"name: ci
on:
push:
jobs:
docker:
runs-on: ubuntu-latest
steps:
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
with:
driver: docker
- name: Build base image
uses: docker/build-push-action@v6
with:
context: "{{defaultContext}}:base"
load: true
tags: my-base-image:latest
- name: Build
uses: docker/build-push-action@v6
with:
build-contexts: |
alpine=docker-image://my-base-image:latest
tags: myimage:latest与容器构建器一起使用
如上一节所示,我们没有使用默认的 docker-container 驱动程序 来构建命名上下文。这是因为该驱动程序无法从 Docker 存储中加载镜像,因为它处于隔离状态。为了解决这个问题,您可以使用本地注册表将您的基础镜像推送到您的工作流中。
# syntax=docker/dockerfile:1
FROM alpine
RUN echo "Hello World"name: ci
on:
push:
jobs:
docker:
runs-on: ubuntu-latest
services:
registry:
image: registry:2
ports:
- 5000:5000
steps:
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
with:
# network=host driver-opt needed to push to local registry
driver-opts: network=host
- name: Build base image
uses: docker/build-push-action@v6
with:
context: "{{defaultContext}}:base"
tags: localhost:5000/my-base-image:latest
push: true
- name: Build
uses: docker/build-push-action@v6
with:
build-contexts: |
alpine=docker-image://:5000/my-base-image:latest
tags: myimage:latest