header image

Code Snippets

Travis-CI Docker Build and Publish

| Last updated:
#!/bin/bash -ev
# TravisCI Docker Build and Publish Script

# Ensure all required environment variables are present
if [ -z "$DOCKER_IMAGE_NAME" ] || \
    [ -z "$DOCKER_USERNAME" ] || \
    [ -z "$DOCKER_PASSWORD" ]; then
    >&2 echo 'Required variable unset, automerging failed'
    exit 1
fi

echo : "
Travis-ci docker build and publishscript
Repo: $TRAVIS_REPO_SLUG
Image: $DOCKER_IMAGE_NAME
"

# Create unique tag from git hash for versioning
branch_head_commit=$(git rev-parse --short=10 HEAD)
image_commit_tag="$DOCKER_IMAGE_NAME_BASE:$branch_head_commit"

# Pull latest app image to cache from ( || true to catch errors if not in registery)
echo "Pulling latest $DOCKER_IMAGE_NAME"
docker pull "$DOCKER_IMAGE_NAME" || true

# Build image (add additional tags here)
echo "Building Image: $DOCKER_IMAGE_NAME"
docker build \
    --cache-from "$DOCKER_IMAGE_NAME" \
    -t "$DOCKER_IMAGE_NAME:latest" \
    -t "$image_commit_tag" \
    .

# Login to docker
echo "$DOCKER_PASSWORD" | docker login -u "$DOCKER_USERNAME" --password-stdin >/dev/null 2>&1

# Publish to dockerhub (pushes all tags)
echo 'Pushing images to docker'
docker push "$DOCKER_IMAGE_NAME" 

Automatically build and publish application container image to dockerhub using Travis-CI

Add docker service to travis build:

services:
  - docker

Add script to project in suitable scripts directory:

./scripts/travis-ci/travis-ci-docker-build-and-deploy.sh

Add the travis-ci-docker-build-and-deploy.sh script to the travis-ci deploy hook (runs after successful tests) to travis.yml:

deploy:
  provider: script
  script: ./scripts/travis-ci/travis-ci-docker-build-and-deploy.sh
  on:
    branch: master

Ensure required environment variables are set in the build. For secret credentials, add to build directly on travis-ci.com, or by using Travis secure values.

DOCKER_USERNAME=<docker-username>
DOCKER_PASSWORD=<docker-password>
DOCKER_IMAGE_NAME=<name-of-docker-image-being-created-and-published>

Note: when adding environment variables as Travis-CI secure values they will only be available in pull requests created by trusted users. Therefore, if an outside user makes a pull request to your repository, they will not have access to your access token and the deployment will fail.

Note: Depending on when your travis-ci account was made, secret may require encrypting with the --com flag. See this stackoverflow for more details