DEV Community

Cover image for How to version Docker images with GitLab CI/CD
Nelson Adonis Hernández
Nelson Adonis Hernández

Posted on

How to version Docker images with GitLab CI/CD

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

Enter fullscreen mode Exit fullscreen mode

2.Build image with ID COMMIT SHA

docker build . -t $CI_REGISTRY/$CI_PROJECT_PATH/$IMAGE_NAME:$CI_COMMIT_SHORT_SHA

Enter fullscreen mode Exit fullscreen mode

3.Get ID from previous image

IMAGE_ID=$(docker images | grep $CI_REGISTRY/$CI_PROJECT_PATH\/$IMAGE_NAME | awk '{print $3}')

Enter fullscreen mode Exit fullscreen mode

4.Retag image latest with digest from previous image

docker tag $IMAGE_ID $CI_REGISTRY/$CI_PROJECT_PATH/$IMAGE_NAME:latest

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Image description

Discussion (0)