Once you know how to create an efficient Docker image, automating the deployment process is a natural next step. This article will teach you how to automate the building and deployment of a Docker image to a registry using GitLab’s Continuous Integration and Deployment (CI/CD) pipeline.
Setting Up the GitLab Pipeline
GitLab CI/CD is an excellent tool for automating the build and deployment of Docker images. We’ll use a .gitlab-ci.yml
file to define the pipeline configuration. This pipeline will have a single stage called builder
for building and pushing the Docker image.
Pipeline Breakdown
Step 1: Variables
variables:
DOCKER_IMAGE_CI: whitecanvas/builder:$CI_COMMIT_TAG
We define a variable DOCKER_IMAGE_CI
that contains the Docker image name along with a tag. $CI_COMMIT_TAG
is a predefined variable in GitLab CI/CD that uses the tag name of the commit if present (this pipeline will be executed only when the user creates a tag number).
Step 2: Authentication
before_script:
- echo "$DOCKERHUB_PASS" | docker login --username $DOCKERHUB_USER --password-stdin
Before executing the main scripts, we log in to Docker Hub using credentials stored in the GitLab CI/CD variables DOCKERHUB_USER
and DOCKERHUB_PASS
.
Step 3: Building and Pushing the Image
amd64_image:
only:
- /(\d+\.)?(\d+\.)?(\*|\d+)/
stage: builder
image: docker:latest
services:
- docker:dind
script:
- cd amd64
- docker build -t $DOCKER_IMAGE_CI .
- docker push $DOCKER_IMAGE_CI
This job runs only when the commit is tagged with a version number (e.g., 1.0.0
). It uses the docker:latest
image and docker:dind
(Docker in Docker) service.
The script performs the following steps:
- Change Directory: Moves into the amd64 directory to where the Dockerfile is located.
- Build the Image: Executes docker build with the tag specified in
DOCKER_IMAGE_CI
. - Push the Image: Pushes the built image to Docker Hub.
Full Contents of the .gitlab-ci.yml
File
Here’s the full contents of the .gitlab-ci.yml
file.
stages:
- builder
variables:
DOCKER_IMAGE_CI: whitecanvas/builder:$CI_COMMIT_TAG
before_script:
- echo "$DOCKERHUB_PASS" | docker login --username $DOCKERHUB_USER --password-stdin
amd64_image:
only:
- /(\d+\.)?(\d+\.)?(\*|\d+)/
stage: builder
image: docker:latest
services:
- docker:dind
script:
- cd amd64
- docker build -t $DOCKER_IMAGE_CI .
- docker push $DOCKER_IMAGE_CI
Automate Your Docker Image Deployments Using GitLab
By leveraging GitLab’s CI/CD pipeline, we can automate the building and deployment of a Docker image.
This setup ensures that every time a new tag is pushed to the repository, our image is automatically built and updated on Docker Hub, streamlining the deployment process and maintaining consistency across releases.
Such automation is critical for efficient and error-free deployments, especially in agile development environments.
If you found this post useful, read our blog for more WordPress tips, trick, and guides.