Search This Blog

Thursday, June 15, 2023

Example gitlab file for docker in docker file with authentication

I ran into a problem in a special docker environment. The docker within this env doesn't allow downloading images from central registries. To bypass this I wrote a dind gitlab-ci.yml which starts a docker in docker image to download the required image and pushes the image into the custom registry. The dind needs to authenticate to push an image to the custom registry or to consume the image from the custom registry. 


Here ist a generic sample gitlab-ci.yml, which downloads and pushes an image. To run this you need the following ci vars configured within gitlab

IMAGE_NAME        : Name of the image to fetch i.e. trion/karma

IMAGE_VERSION   : Version of the image i.e. latest

DOCKER_AUTH_CONFIG: String with a valid docker auth config for your custom repo

CI_REGISTRY: Link to your docker registry



image: docker:20.10.24

variables:
    DOCKER_HOST: tcp://docker:2375
    DOCKER_TLS_CERTDIR: ""

services:
    - name: docker:20.10.24-dind
        entrypoint: ["dockerd-entrypoint.sh"]
        command: ["--insecure-registry", "custom.registry.mycomp.org:443"]

before_script:
    - docker info

# job for fetching any image in the var $IMAGE_NAME:$IMAGE_VERSION

deploy-generic-image:
    stage: build
    when: manual
    tags:
        - docker-in-docker
        - PROD
    before_script:
        - mkdir -p ~/.docker
        - echo $DOCKER_AUTH_CONFIG > ~/.docker/config.json
    script:
        - echo "Pulling $IMAGE_NAME:$IMAGE_VERSION"
        - docker pull $IMAGE_NAME:$IMAGE_VERSION
        - docker images
        - docker image tag $IMAGE_NAME:$IMAGE_VERSION $CI_REGISTRY/$IMAGE_NAME:$IMAGE_VERSION
        - docker images
        - docker push $CI_REGISTRY/$IMAGE_NAME:$IMAGE_VERSION



If you don't like the docker_auth_config you could also add the login info in the before_script section like that

before_script:
    - echo "$CI_JOB_TOKEN" | docker login -u "$CI_REGISTRY_USER" --password-stdin $CI_REGISTRY



But to consume the image within your gitlab-ci.yml you will need the docker_auth_config.