[分享] GitLab CI/CD与Kaniko结合构建容器镜像

Building containers without privileged mode

Reference

Kaniko

kaniko is a tool to build container images from a Dockerfile, inside a container or Kubernetes cluster.

kaniko doesn’t depend on a Docker daemon and executes each command within a Dockerfile completely in userspace. This enables building container images in environments that can’t easily or securely run a Docker daemon, such as a standard Kubernetes cluster.

Setup

Demo Project: https://jihulab.com/cltian/building-containers-without-privileged-mode

Yaml file:

stages:
  - build

variables:
  KANIKO_CACHE_ARGS: "--cache=true --cache-copy-layers=true --cache-ttl=24h"
  IMAGE_LABELS: >
    --label commit.sha=$CI_COMMIT_SHORT_SHA
  IMAGE_BUILD_ARGS: >
    --build-arg APPNAME=go-zero-greet
    --build-arg GOPROXY=https://proxy.golang.com.cn,direct

.build_with_kaniko:
  image: 
    name: lolspider/kaniko-project-executor:debug
    entrypoint: [""]
  stage: build
  script:
    - mkdir -p /kaniko/.docker
    - echo "{\"auths\":{\"${CI_REGISTRY}\":{\"auth\":\"$(printf "%s:%s" "${CI_REGISTRY_USER}" "${CI_REGISTRY_PASSWORD}" | base64 | tr -d '\n')\"}}}" > /kaniko/.docker/config.json
    - >-
      /kaniko/executor
      --context dir:///${CI_PROJECT_DIR}
      --dockerfile ${CI_PROJECT_DIR}/Dockerfile 
      --destination "$CI_REGISTRY_IMAGE:$CI_PIPELINE_IID" $KANIKO_CACHE_ARGS $IMAGE_LABELS $IMAGE_BUILD_ARGS


build-and-push-to-dockerhub:
  stage: build
  extends: .build_with_kaniko
  environment:
    name: push-to-docker-hub

build-and-push-to-gitlab-registry:
  stage: build
  extends: .build_with_kaniko
  environment:
    name: push-to-gitlab-registry

This project implements two ways building docker images:

  • push to docker hub

  • push to gitlab registry

Before running this ci project, you should check the four Protected Variables: