Using to build Docker images

Oct 23, 2015 recently released support to use Docker inside the CI pipeline and you can read the announcement here.

In this post, I will show you how to use this feature to build Docker images and store them on a Docker registry using

I’ll discuss 2 methods, one using only Docker commands and another using Rocker which I recently discussed about here.

The complete source code is available here.

Storing your docker registry credentials securely

The first step is to store you docker registry credentials in the .travis.yml file. We will store them in some environment variables.

You can read more about this on website here.

$ travis encrypt
$ travis encrypt DOCKER_USER=username
$ travis encrypt DOCKER_PASS=password

And then store the secure version in your .travis.yml file.

We will add a comment on the line to help us remember which line contains which environment variable.

We will also add an environment variable containing the 8 first characters of the git commit hash.

    - secure: "UkF2CHX0lUZ...VI/LE=" # DOCKER_EMAIL
    - secure: "Z3fdBNPt5hR...VI/LE=" # DOCKER_USER
    - secure: "F4XbD6WybHC...VI/LE=" # DOCKER_PASS

Creating and shipping the Docker image

In the after_success section of the .travis.yml file, we log on Docker Hub registry, then we build the image.

We also tag the generated image with:

  • the short git commit hash
  • the travis build number
  • latest if it is the master branch, otherwise the name of the branch

And finally we push it on the Docker Hub registry

  - docker login -e $DOCKER_EMAIL -u $DOCKER_USER -p $DOCKER_PASS
  - export REPO=sebestblog/travis-demo
  - export TAG=`if [ "$TRAVIS_BRANCH" == "master" ]; then echo "latest"; else echo $TRAVIS_BRANCH ; fi`
  - docker build -f Dockerfile -t $REPO:$COMMIT .
  - docker tag $REPO:$COMMIT $REPO:$TAG
  - docker tag $REPO:$COMMIT $REPO:travis-$TRAVIS_BUILD_NUMBER
  - docker push $REPO

The complete source code is available here.

Alternative solution using Rocker

An alternative solution is to use Rocker that we presented in a previous post.

  - curl -O -L
  - tar xvfz rocker-0.2.2_linux_amd64.tar.gz