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:dindservice to the job. - Run
docker loginwith 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-stdinso 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
How to Deploy to Amazon ECS With GitLab CI/CDDeploy a new image to Amazon ECS from GitLab CI/CD by forcing a new deployment on the service with aws ecs up…
How to Deploy to Kubernetes With kubectl in GitLab CI/CDDeploy to Kubernetes from GitLab CI/CD using kubectl set image and kubectl rollout status, updating a Deploym…