How to build and publish your images in Docker Hub automatically

2 minute read

Header

If you have an account on Docker Hub, what I recommend you, this post will show you how to build and publish your Docker images automatically from your GitHub repositories. Docker Hub allows also to connect Bitbucket’s repositories.

First of all, you need to have a Git repository with a proper Dockerfile like this one Text Extractor. Then, go to your Docker Hub account and click on the “Repositories” tab to show all the repositories (Docker Images). To create a new repository just click on the “Create Repository” button as shown in the picture:

How to create a repository

At this point you can set the repository’s name, its description and, within the “Build Settings (optional)” section, you can specify the service where the source code repository is hosted: GitHub or Bitbucket, at this moment.

Repository properties

Once you connect your GitHub’s account the “Build configurations” page is displayed:

Build configurations

On this page the default values are good enough, but the important part is the BUILD RULES section which allows you to add the build rules that will trigger the image build process. The following are the parameters that can be configured:

  • Source Type: the build rule can monitor either a Tag or Branch.
  • Source: this is a regular expression to be applied on the Source Type.
  • Docker Tag: this is the tag to be added on the Docker Image.
  • Dockerfile location: the name of the Dockerfile in case is not the default one
  • Build Context: where is the Dockerfile located.

The following picture shows the Build rules I typically use to trigger the build of my Docker images:

Build rule example

Source: /^v([0-9.]+)$/
Docker Tag: release-{sourceref}

With the above parameters, every time you create a tag on your GitHub repository containing a v on its name (i.e. v1.0.0) the build rule will be obeyed and Docker Hub will build a Docker Image tagged as for example image:1.0.0.

To create a release of your code, just click on the Code tab and then click on the tag link, which will allow you to tag your latest commit as a release. On the following picture we can see how I tagged my source code as v0.0.1 which match the regex pattern /^v([0-9.]+)$/ of the Build rule set on Docker Hub.

Release tag in GitHub

The following picture shows how Docker Hub starts the image building process:

Building the image

By clicking on the “Builds” tab you can see all the builds triggered and their status over a time period.

Build activity