带有 GitHub Actions 的命名上下文
您可以定义
其他构建上下文FROM name
,并使用或在 Dockerfile 中访问它们--from=name
。当 Dockerfile 定义同名的阶段时,它会被覆盖。
这对于 GitHub Actions 非常有用,可以重用其他构建的结果或将图像固定到工作流程中的特定标签。
将图像固定到标签
替换alpine:latest
为固定的:
# syntax=docker/dockerfile:1
FROM alpine
RUN echo "Hello World"
name: ci
on:
push:
branches:
- "main"
jobs:
docker:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Build
uses: docker/build-push-action@v5
with:
context: .
build-contexts: |
alpine=docker-image://alpine:3.19
tags: myimage:latest
在后续步骤中使用图像
默认情况下,
Docker Setup Buildx
操作用作docker-container
构建驱动程序,因此不会自动加载构建的 Docker 映像。
通过命名上下文,您可以重用构建的图像:
# syntax=docker/dockerfile:1
FROM alpine
RUN echo "Hello World"
name: ci
on:
push:
branches:
- "main"
jobs:
docker:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
with:
driver: docker
- name: Build base image
uses: docker/build-push-action@v5
with:
context: ./base
file: ./base/Dockerfile
load: true
tags: my-base-image:latest
- name: Build
uses: docker/build-push-action@v5
with:
context: .
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:
branches:
- "main"
jobs:
docker:
runs-on: ubuntu-latest
services:
registry:
image: registry:2
ports:
- 5000:5000
steps:
- name: Checkout
uses: actions/checkout@v4
- 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@v5
with:
context: ./base
file: ./base/Dockerfile
tags: localhost:5000/my-base-image:latest
push: true
- name: Build
uses: docker/build-push-action@v5
with:
context: .
build-contexts: |
alpine=docker-image://localhost:5000/my-base-image:latest
tags: myimage:latest