
Containerizing Applications in GitLab CI/CD
Docker Integration in GitLab CI/CD
Building container images inside CI/CD pipelines ensures that your application builds are repeatable, uniform, and deployment-ready. This guide details how to build and store Docker containers using the GitLab Container Registry.
1. Setting Up Docker-in-Docker (DinD)
To run Docker commands inside a pipeline job, we must use a Docker-capable runner and specify the DinD service:
build_image:
stage: build
image: docker:24.0.5
services:
- docker:24.0.5-dind
variables:
DOCKER_TLS_CERTDIR: "/certs"
script:
- docker build -t my-app .
2. Pushing to GitLab Container Registry
Every GitLab project comes with a built-in container registry. You can authenticate using pre-defined pipeline variables ($CI_REGISTRY_USER, $CI_REGISTRY_PASSWORD, and $CI_REGISTRY):
publish_image:
stage: deploy
image: docker:24.0.5
services:
- docker:24.0.5-dind
script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
- docker build -t $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA -t $CI_REGISTRY_IMAGE:latest .
- docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
- docker push $CI_REGISTRY_IMAGE:latest
3. Promoting Images
For release staging, it is common to pull a verified container image tagged with a Git commit SHA, verify it in a smoke-test environment, and promote it to stable or production:
promote_image:
stage: deploy
script:
- docker pull $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
- docker tag $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA $CI_REGISTRY_IMAGE:stable
- docker push $CI_REGISTRY_IMAGE:stable
This ensures that only fully tested images are ever deployed to production servers.
Notes & Reviews