Pushing to Docker Hub from GitLab CI

Many of my projects now involve building a Docker image. The image is generally pushed to a registry as part of a CI workflow. This is how I push an image to Docker Hub from GitLab CI.

The Problem

On my first few attempts to get this working I kept on running into the following error:

denied: requested access to the resource is denied

I could build the image. But I just couldn’t push it.

The Solution

The solution was to be explicit about the registry. Below is an extract from my .gitlab-ci.yml.

  IMAGE_REGISTRY: docker.io
  IMAGE_NAME: datawookie/test

  image: docker:stable
  stage: build
  interruptible: true
    - master
    - docker:dind
    - env
    - docker info
    - docker pull $TAG_LATEST || true
    - docker build --cache-from $TAG_LATEST -t $TAG_COMMIT -t $TAG_LATEST .
    - docker push $TAG_LATEST
    - docker push $TAG_COMMIT

I set up a few environment variables:

  • IMAGE_REGISTRY — The name of the Docker Hub image registry.
  • IMAGE_NAME — The name of my image, consisting of my Docker Hub username and the actual image name.
  • TAG_LATEST — The full image path including the registry and tagged as latest.
  • TAG_COMMIT — The full image path including the registry and tagged with the commit SHA.

This workflow uses the docker:dind service (the “Docker in Docker” image). For this to work you’ll need to use a GitLab runner with the --docker-privileged option.

See also these related posts: