Skip to content
Latchkey

How to Deploy a Docker Image to Docker Hub With GitLab CI/CD

A docker login with a Docker Hub access token, run inside docker:dind, lets the job push a tagged image to an external registry.

Run the job with the docker:dind service, log in to Docker Hub with an access token, then build and push the image tagged by the commit SHA and latest.

Steps

  • Create a Docker Hub access token and store it as a masked CI variable.
  • Add the docker:dind service to the job.
  • Run docker login with the token.
  • Build and push the image with a SHA tag and latest.

.gitlab-ci.yml

.gitlab-ci.yml
deploy_image:
  stage: deploy
  image: docker:27
  services:
    - docker:27-dind
  variables:
    IMAGE: docker.io/myorg/myapp
  rules:
    - if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
  script:
    - echo "$DOCKERHUB_TOKEN" | docker login -u "$DOCKERHUB_USER" --password-stdin
    - docker build -t "$IMAGE:$CI_COMMIT_SHORT_SHA" -t "$IMAGE:latest" .
    - docker push "$IMAGE:$CI_COMMIT_SHORT_SHA"
    - docker push "$IMAGE:latest"

Gotchas

  • Use --password-stdin so the token never appears in the job log or process list.
  • Use a scoped access token, not your account password, and rotate it if leaked.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →