Docker Hub supports connecting both your GitHub and BitBucket accounts so that when you push to a git repo on either of those repository hosts (once you’ve set them up as sources for a docker image), then Docker Hub will auto build the image for you. However, Docker Hub doesn’t support auto builds from GitLab, and so for those people who want to have their Docker images automatically built they’ll need to come up with another solution. This is a use case that I’ve had to come up with a solution for, and so to share with the community here it is:
The first thing you’ll need to do is to enable GitLab pipelines for your git repo with that has the Dockerfile you want to build. You can find the setting to enable this under the “Permissions” section in the “General” settings page. Now that pipelines are enabled you’ll need to let GitLab pipelines be able to run something.
The start of the
.gitlab-ci.yml file will need to define both the image that will be used to build your image, and any services required. In our cause the image being used is the docker image so that the docker binary is available to us, and the service required for us is the docker-in-docker service which will allow us to run docker commands.
image: docker:latest services: - docker:dind
Before anything is run, you’ll need to authenticate against Docker Hub. Instead of exposing your credentials in your git repository you can configure environment variables where you can store your Docker Hub username, and password. Below you’ll find the environment variables prefixed with a
before_script: - docker login -u $DOCKERHUB_USER -p $DOCKERHUB_KEY
Now we can finally build the image. You’ll need to switch out the
$DOCKERHUB_USER/imagename with the name of the image you want pushed (it will use your Docker Hub userame as the namespace). This is configured to only run on the
master branch of your git repo so that if you have branched off
master those potentially unstable branches won’t override the image on Docker Hub.
build_and_release: script: - docker build --pull -t $DOCKERHUB_USER/imagename . - docker push $DOCKERHUB_USER/imagename:latest only: - master
Combine the three YAML partials above into one file, in order, name it
.gitlab-ci.yml, set up the environment variables, and put the file in your git repo. Now whenever you commit to your master branch on GitLab it will build and release a docker image for you.