MultiArchDocker

nicolaw 11th February 2022 at 9:47pm
.gitlab-ci.yml Docker GitLab

It sounds like there's some kind of squabble going on with the Docker and buildx developers that means the official docker.io/docker images aren't including buildx. Le sigh.

.dind:
  image: docker:latest
  services:
    - name: docker:dind
      alias: docker
      command: ["--experimental"]
  variables:
    DOCKER_HOST: tcp://docker:2376
    DOCKER_TLS_VERIFY: "1"
    DOCKER_TLS_CERTDIR: "/certs"
    DOCKER_CERT_PATH: "/certs/client"
    MULTIARCH_PLATFORMS: "linux/arm64,linux/amd64,linux/arm/v6,linux/arm/v7"
  before_script:
    - echo $CI_REGISTRY_PASSWORD | docker login -u "$CI_REGISTRY_USER" --password-stdin "$CI_REGISTRY"
    - >
      [[ -z "$DOCKERHUB_TOKEN" ]] || cat "$DOCKERHUB_TOKEN" | docker login -u "$DOCKERHUB_USERNAME" docker.io

    - mkdir -p ~/.docker/cli-plugins
    - apk add -q dpkg curl && export ARCH="$(dpkg --print-architecture | sed -e 's/.*-//')"
    - curl -sSLo ~/.docker/cli-plugins/docker-buildx "https://github.com/docker/buildx/releases/download/v0.7.1/buildx-v0.7.1.linux-$ARCH"
    - chmod a+x ~/.docker/cli-plugins/docker-buildx

    - docker run --rm --privileged multiarch/qemu-user-static --reset -p yes
    - [[ -z "$DEBUG" ]] || docker version
    - [[ -z "$DEBUG" ]] || docker buildx ls
    - docker context create builder
    - docker buildx create --name multiarch --driver docker-container --use builder
    - [[ -z "$DEBUG" ]] || docker buildx inspect --bootstrap
        
.multiarch-container:
  extends: .dind
  variables:
    CACHE_IMAGE_NAME: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
  script:
    - >-
      docker buildx build -f Dockerfile .
      --progress plain
      --platform "$MULTIARCH_PLATFORMS"
      --pull --push
      --cache-from="type=registry,ref=${CACHE_IMAGE_NAME}"
      --cache-to="type=registry,ref=${CACHE_IMAGE_NAME}"
      --build-arg BUILD_DATE="$(date +'%Y-%m-%d')"
      --build-arg VCS_REF="$CI_COMMIT_SHA"
      $(for tag in $TAGS ; do echo -t $tag ; done)
    - for tag in $TAGS ; do docker manifest inspect $tag ; done
        
build:container:
  stage: build
  extends: .multiarch-container
  variables:
    TAGS: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG-$CI_COMMIT_SHORT_SHA
        
upload:container:
  stage: upload
  extends: .multiarch-container
  variables:
    TAGS: docker.io/$DOCKERHUB_USERNAME/$CI_PROJECT_NAME:$CI_COMMIT_TAG docker.io/$DOCKERHUB_USERNAME/$CI_PROJECT_NAME:latest
  rules:
    - if: '$CI_COMMIT_TAG =~ /^v[0-9]{1,4}\.[0-9]{1,4}\.[0-9]{1,4}$/'