使用 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.20
tags: myimage:latest
在後續步驟中使用映像檔
預設情況下,Docker Setup Buildx動作使用 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://localhost:5000/my-base-image:latest
tags: myimage:latest