For this example we will use GitLab Container Registry and we will version the images by commit
Variables of GitLab
CI_REGISTRY_USER: User actually of GitLab
CI_REGISTRY_PASSWORD: Password actually of GitLab
CI_REGISTRY: "registry.gitlab.com"
CI_PROJECT_PATH: "gitlab-example/my-project"
CI_COMMIT_SHORT_SHA: Recent commit ID
1.Docker Login (GitLab Container registry)
docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
2.Build image with ID COMMIT SHA
docker build . -t $CI_REGISTRY/$CI_PROJECT_PATH/$IMAGE_NAME:$CI_COMMIT_SHORT_SHA
3.Get ID from previous image
IMAGE_ID=$(docker images | grep $CI_REGISTRY/$CI_PROJECT_PATH\/$IMAGE_NAME | awk '{print $3}')
4.Retag image latest with digest from previous image
docker tag $IMAGE_ID $CI_REGISTRY/$CI_PROJECT_PATH/$IMAGE_NAME:latest
5.Push image latest and commit sha
docker push $CI_REGISTRY/$CI_PROJECT_PATH/$IMAGE_NAME:$CI_COMMIT_SHORT_SHA
docker push $CI_REGISTRY/$CI_PROJECT_PATH/$IMAGE_NAME:latest
6.Pipeline
build:
image: docker:19.03.12
stage: build
services:
- docker:19.03.12-dind
rules:
- if: $CI_PIPELINE_SOURCE == "push"
variables:
IMAGE_NAME: "my-app"
script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
# BUILD IMAGE WITH COMMIT SHA
- docker build . -t $CI_REGISTRY/$CI_PROJECT_PATH/$IMAGE_NAME:$CI_COMMIT_SHORT_SHA
# RETAG IMAGE LATEST WITH DIGEST FROM PREVIOUS IMAGE
- IMAGE_ID=$(docker images | grep $CI_REGISTRY/$CI_PROJECT_PATH\/$IMAGE_NAME | awk '{print $3}')
- docker tag $IMAGE_ID $CI_REGISTRY/$CI_PROJECT_PATH/$IMAGE_NAME:latest
# PUSH IMAGE COMMIT SHA and LATEST
- docker push $CI_REGISTRY/$CI_PROJECT_PATH/$IMAGE_NAME:$CI_COMMIT_SHORT_SHA
- docker push $CI_REGISTRY/$CI_PROJECT_PATH/$IMAGE_NAME:latest
8.Images in Docker Registry
The latest image will always point to the latest version
68713c41 Published 1 minute ago
41.58 MiB Digest: 2fd477a
latest Published 1 minute ago
41.58 MiB Digest: 2fd477a
Top comments (1)
Thanks for your help, but I finally found a better solution:
Note:
I personally contract
$CI_REGISTRY/$CI_PROJECT_PATH/$IMAGE_NAME
to$CI_REGISTRY_IMAGE
(also is a GitLab default)