1 # Build and push a Docker image with CI/CD.
2 # Docker-in-Docker documentation: https://docs.gitlab.com/ee/ci/docker/using_docker_build.html
4 # By default builds are tagged with their branch name and pushed to the
5 # Gitlab Docker Registry. If DOCKER_TAG_LATEST is set to true, builds on
6 # the $DOCKER_LATEST_BRANCH are also tagged and pushed as ":latest"
8 # Scheduled builds can be enabled on a Gitlab schedule by specifying
9 # DOCKER_SCHEDULE = "true" in variables
12 # Docker registry where images will be pushed
13 DOCKER_REGISTRY: "$CI_REGISTRY"
14 DOCKER_USERNAME: "$CI_REGISTRY_USER"
15 DOCKER_TOKEN: "$CI_REGISTRY_PASSWORD"
16 # Whether or to push images after they're built
18 # TODO: Conditionally include '--file' to docker build to reduce need
19 # to always define FILEPATH when BUILDCONTEXT is set
20 DOCKER_FILEPATH: "Dockerfile"
21 DOCKER_BUILDCONTEXT: "."
22 DOCKER_IMAGE: "$CI_REGISTRY_IMAGE"
23 # If LATEST_TAG is set to true, builds on the $DOCKER_LATEST_BRANCH
24 # will be tagged and pushed with ":latest"
25 DOCKER_LATEST_TAG: "true"
26 DOCKER_LATEST_BRANCH: "$CI_DEFAULT_BRANCH"
28 .docker-build-and-push: &docker-build-and-push
35 - docker login -u "$DOCKER_USERNAME" -p "$DOCKER_TOKEN" $DOCKER_REGISTRY
37 # Warm the cache by fetching the latest image. There's no guarantee
38 # the image will already exist on the runner.
39 - docker pull "$DOCKER_IMAGE:${CI_COMMIT_REF_SLUG}" || true
43 --cache-from "$DOCKER_IMAGE:${CI_COMMIT_REF_SLUG}"
44 --file "$DOCKER_FILEPATH"
45 --tag "$DOCKER_IMAGE:${CI_COMMIT_REF_SLUG}"
48 if [[ "$CI_COMMIT_BRANCH" == "$DOCKER_LATEST_BRANCH" && "$DOCKER_LATEST_TAG" == "true" ]]; then
49 docker tag "$DOCKER_IMAGE:${CI_COMMIT_REF_SLUG}" "$DOCKER_IMAGE"
52 # Push docker images if DOCKER_PUSH is set
53 if [[ "$DOCKER_PUSH" == "true" ]]; then
54 docker push "$DOCKER_IMAGE:${CI_COMMIT_REF_SLUG}"
55 # Push ':latest' if LATEST_TAG is true
56 if [[ "$CI_COMMIT_BRANCH" == "$DOCKER_LATEST_BRANCH" && "$DOCKER_LATEST_TAG" == "true" ]]; then
57 docker push "$DOCKER_IMAGE"
61 - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
63 # Gitlab does not have a way of specifying which jobs are scheduled,
64 # so an extra variable is needed in order to signify docker build
65 # should be picked up by the schedule run.
66 - if: $CI_PIPELINE_SOURCE == "schedule" && $DOCKER_SCHEDULE != "true"
68 - if: '$CI_COMMIT_BRANCH == $DOCKER_LATEST_BRANCH'
69 - if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'