|
| 1 | +# Named contexts |
| 2 | + |
| 3 | +You can define [additional build contexts](https://docs.docker.com/engine/reference/commandline/buildx_build/#build-context) |
| 4 | +that can be accessed in your Dockerfile with `FROM name` or `--from=name`. When |
| 5 | +Dockerfile defines a stage with the same name it is overwritten. |
| 6 | + |
| 7 | +This can be useful with GitHub Actions to reuse results from other builds or |
| 8 | +pin an image to a spcific tag in your workflow. |
| 9 | + |
| 10 | +## Pin image to a specific tag |
| 11 | + |
| 12 | +Replace `alpine:latest` with a pinned one: |
| 13 | + |
| 14 | +```dockerfile |
| 15 | +# syntax=docker/dockerfile:1 |
| 16 | +FROM alpine |
| 17 | +RUN echo "Hello World" |
| 18 | +``` |
| 19 | + |
| 20 | +```yaml |
| 21 | +name: ci |
| 22 | + |
| 23 | +on: |
| 24 | + push: |
| 25 | + branches: |
| 26 | + - 'main' |
| 27 | + |
| 28 | +jobs: |
| 29 | + docker: |
| 30 | + runs-on: ubuntu-latest |
| 31 | + steps: |
| 32 | + - |
| 33 | + name: Checkout |
| 34 | + uses: actions/checkout@v3 |
| 35 | + - |
| 36 | + name: Set up Docker Buildx |
| 37 | + uses: docker/setup-buildx-action@v2 |
| 38 | + - |
| 39 | + name: Build |
| 40 | + uses: docker/build-push-action@v3 |
| 41 | + with: |
| 42 | + context: . |
| 43 | + build-contexts: | |
| 44 | + alpine=docker-image://alpine:3.16 |
| 45 | + tags: myimage:latest |
| 46 | +``` |
| 47 | +
|
| 48 | +## Usage of the built image in other build steps |
| 49 | +
|
| 50 | +By default, the [`setup-buildx` action](https://github.com/docker/setup-buildx-action#about) |
| 51 | +uses `docker-container` as a build driver, so built Docker images are not |
| 52 | +available in the builder container. |
| 53 | + |
| 54 | +With named contexts you can reuse the built image: |
| 55 | + |
| 56 | +```dockerfile |
| 57 | +# syntax=docker/dockerfile:1 |
| 58 | +FROM alpine |
| 59 | +RUN echo "Hello World" |
| 60 | +``` |
| 61 | + |
| 62 | +```yaml |
| 63 | +name: ci |
| 64 | +
|
| 65 | +on: |
| 66 | + push: |
| 67 | + branches: |
| 68 | + - 'main' |
| 69 | +
|
| 70 | +jobs: |
| 71 | + docker: |
| 72 | + runs-on: ubuntu-latest |
| 73 | + steps: |
| 74 | + - |
| 75 | + name: Checkout |
| 76 | + uses: actions/checkout@v3 |
| 77 | + - |
| 78 | + name: Set up Docker Buildx |
| 79 | + uses: docker/setup-buildx-action@v2 |
| 80 | + - |
| 81 | + name: Build base image |
| 82 | + uses: docker/build-push-action@v3 |
| 83 | + with: |
| 84 | + context: base |
| 85 | + load: true |
| 86 | + tags: my-base-image:latest |
| 87 | + - |
| 88 | + name: Build |
| 89 | + uses: docker/build-push-action@v3 |
| 90 | + with: |
| 91 | + context: . |
| 92 | + build-contexts: | |
| 93 | + alpine=docker-image://my-base-image:latest |
| 94 | + tags: myimage:latest |
| 95 | +``` |
0 commit comments