企業運維實踐-丟棄手中的 docker build , 使用Kaniko直接在Kubernetes集群或Containerd環境中快速進行構建推送容器鏡像

關注「WeiyiGeek」公眾號

設為「特別關注」每天帶你玩轉網路安全運維、應用開發、物聯網IOT學習!

希望各位看友【關注、點贊、評論、收藏、投幣】,助力每一個夢想。

帥哥(靚仔)、美女,點個關注後續不迷路


本章目錄


首發地址: //mp.weixin.qq.com/s/wchtH6i0xKrIrqSuYKmWkg

原文地址: //blog.weiyigeek.top/2022/9-1-684.html


0x00 前言簡述

快速介紹

什麼是Kaniko?

kaniko 是一個在容器或 Kubernetes 集群內從 Dockerfile 構建容器鏡像的工具 ( Build Container Images In Kubernetes )。

官方介紹

溫馨提示: kaniko不是Google官方發布支援的產品.

為啥用Kaniko?

由於 kaniko 不依賴於 Docker 守護進程,並且完全在用戶空間中執行 Dockerfile 中的每個命令,這使得能夠在輕鬆或安全地運行在無Docker守護程式的環境(如標準Kubernetes集群 V1.24.x)中構建容器映像。
在 Kubernetes V1.24.x 版本之後默認採用 containerd.io 作為預設的cri,不在支援 docker-shim 意味著我們不需要安裝 docker 環境

Kaniko 是如何工作的?

kaniko 執行器鏡像負責從 Dockerfile 構建鏡像並將其推送到註冊表,其流程大致如下:

  • 首先在執行者影像中,我們提取基礎鏡像的文件系統(Dockerfile 中的 FROM 鏡像)。
  • 其次我們執行 Dockerfile 中的命令,之後在用戶空間中對文件系統進行快照每一個。
  • 然後在每個命令之後,我們將一層更改的文件附加到基礎 影像(如果有)並更新影像元數據。

Kaniko 已知功能問題

  • kaniko 不支援構建 Windows 容器。
  • kaniko 不支援 v1 Registry API。(由於其不安全性當前基本都是使用V2協議, 例如 Harbor)
  • kaniko 不支援在除官方kaniko映像之外的任何Docker映像中運行二進位Kanico可執行文件(即YMMV)。

kaniko 構建上下文

描述: kaniko 的構建上下文與您發送 Docker 守護程式以進行映像構建的構建上下文非常相似;它代表一個包含 Dockerfile 的目錄,kaniko 將使用它來構建您的影像。
例如, Dockerfile 中的 COPY 命令應該引用構建上下文中的文件, 所以您需要將構建上下文存儲在 kaniko 可以訪問的位置。

目前kaniko 支援以下存儲解決方案:

  • GCS Bucket
  • S3 Bucket
  • Azure Blob Storage
  • Local Directory
  • Local Tar
  • Standard Input
  • Git Repository

運行 kaniko 時,使用 --context 帶有適當前綴的標誌指定構建上下文的位置, 如果您不指定前綴 kaniko 將假定一個本地目錄, 該參數可用值:

Source Prefix Example
Local Directory dir://[path to a directory in the kaniko container] dir:///workspace
Local Tar Gz tar://[path to a .tar.gz in the kaniko container] tar://path/to/context.tar.gz
Standard Input tar://[stdin] tar://stdin
GCS Bucket gs://[bucket name]/[path to .tar.gz] gs://kaniko-bucket/path/to/context.tar.gz
S3 Bucket s3://[bucket name]/[path to .tar.gz] s3://kaniko-bucket/path/to/context.tar.gz
Azure Blob Storage //[account].[azureblobhostsuffix]/[container]/[path to .tar.gz] //myaccount.blob.core.windows.net/container/path/to/context.tar.gz
Git Repository git://[repository url][#reference][#commit-id] git://github.com/acme/myproject.git#refs/heads/mybranch#

例如,要使用名為 kaniko-bucket 的 GCS 存儲桶,您需要傳入 --context=gs://kaniko-bucket/path/to/context.tar.gz

溫馨提示:kaniko 允許的唯一標準輸入是 .tar.gz 格式, 如果要創建壓縮 tar,您可以運行 tar -C <path to build context> -zcvf context.tar.gz .命令。

$ ls cache/
Dockerfile

# 壓縮上下文目錄
$ tar -C cache/ -zcvf context.tar.gz .
./
./Dockerfile

# 查看壓縮文件
$ tar -ztvf context.tar.gz
drwxr-xr-x root/root         0 2022-09-08 23:03 ./
-rw-r--r-- root/root        52 2022-09-08 23:04 ./Dockerfile

kaniko 快取構建

  • Caching Layers :kaniko 可以在遠程存儲庫中快取由RUN(由flag–cache-RUN-layers配置)和COPY(由flag–cache-COPY-layeers配置)命令創建的層。

    在執行命令之前 kaniko 會檢查層的快取,如果存在 kaniko將拉取並提取快取層,而不是執行命令。如果沒有 kaniko將執行命令,然後將新創建的層推送到快取。
    用戶可以通過設置 --cache=true 標誌選擇快取,並且可以通過--cache-repo 標誌提供用於存儲快取層的遠程存儲庫, 如果未提供此標誌則將從提供的--destination推斷快取的repo。
    溫馨提示: 在快取未命中後,kaniko無法從快取中找到讀取層,所有後續層都將在本地構建,而無需諮詢快取。

  • Caching Base Images: kaniko 可以將影像快取在本地目錄中,該目錄可以卷裝載到KanikoPod中。為此必須首先填充快取, 我們在 gcr.io/kaniko-project/warmer 提供了一個kaniko快取預熱映像:

    –image : 指定所需任意數量的影像, 填充快取後 使用與上述相同的 --cache=true 標誌選擇快取, 本地快取的位置通過 --cache-dir 標誌提供,默認為 /cache 與快取預熱器一樣, 在實踐中通常與 Kubernetes 集群和持久快取卷一起使用。
    示例: docker run -v $(pwd):/workspace gcr.io/kaniko-project/warmer:latest --cache-dir=/workspace/cache --image=<image to cache> --image=<another image to cache>


0x01 部署使用

環境依賴

  • kaniko 影像鏡像
  • 一個 Kubernetes 集群 或者 一個 Containerd 容器運行環境。
  • 一個 dockerhub 帳戶 用於將構建的影像公開。

小試牛刀之在Kubernetes集群中構建並發布鏡像

描述: 此處我們準備在一個K8S集群中使用kaniko提供的鏡像,按照提供的Dockerfile指令進行鏡像構建,並上傳到 docker hub 倉庫中,以下為操作流程、

操作流程
步驟 01.首先, 為了加快構建速度, 我們提前在集群中拉取 gcr.io/kaniko-project/executor 鏡像到本地, 由於中國無法直接拉取此處我採用這篇【使用Aliyun容器鏡像服務對海外gcr、quay倉庫鏡像進行鏡像拉取構建】 文章中的方法進行拉取構建國外gcr.io倉庫中的鏡像。

# 此處我已經創建了中國可以訪問拉取的 executor 鏡像, 不想在Aliyun容器鏡像服務中進行創建拉取的朋友可以直接使用如下倉庫地址。
registry.cn-hangzhou.aliyuncs.com/weiyigeek/kaniko-executor:latest

# 使用 ctr 或者 crictl 進行鏡像拉取
$ crictl pull registry.cn-hangzhou.aliyuncs.com/weiyigeek/kaniko-executor:latest
$ crictl images | grep "kaniko-executor"
registry.cn-hangzhou.aliyuncs.com/weiyigeek/kaniko-executor  latest  da9592dbe1de3   25.8MB

步驟 02.準備一個 Dockerfile 此處將 registry.cn-hangzhou.aliyuncs.com/weiyigeek/kaniko-executor 鏡像打包上傳到hub中作為演示。

# 創建存放dockerfile目錄以及持久化快取目錄
mkdir -vp /storage/dev/soft/kaniko/{cache,demo}
cd /storage/dev/soft/kaniko/demo
tee dockerfile <<'EOF'
FROM registry.cn-hangzhou.aliyuncs.com/weiyigeek/kaniko-executor:latest
LABEL [email protected] BUILDTYPE=kaniko
EOF

步驟 03.創建一個授權令牌的 Secret , 此處以公共的docker hub為例。

# 語法:
~$ kubectl create secret docker-registry dockerhub --docker-server=<your-registry-server> --docker-username=<your-name> --docker-password=<your-pword> --docker-email=<your-email>

# 參數值:
# <your-registry-server> is your Private Docker Registry FQDN. (//index.docker.io/v1/ for DockerHub)
# <your-name> is your Docker username.
# <your-pword> is your Docker password.
# <your-email> is your Docker email.

# 創建示例: 此 docker-registry 將在 pod.yaml 配置中使用
~$ kubectl create secret docker-registry dockerhub \
--docker-server=//index.docker.io/v1/ \
--docker-username=weiyigeek \
--docker-password=PASSWORD \
[email protected]
# secret/dockerhub created

# 查看創建的 secrets 情況
~$ kubectl get secrets dockerhub
NAME        TYPE                             DATA   AGE
dockerhub   kubernetes.io/dockerconfigjson   1      16s

~$ kubectl get secrets dockerhub -o yaml
apiVersion: v1
data:
  .dockerconfigjson: eyJhdXRo*******VhsbE1qQXhPUT09In19fQ==
kind: Secret
metadata:
  name: dockerhub

步驟 04.創建一個在k8s集群中運行的Pod,其資源清單如下所示:

tee kaniko.yaml <<'EOF'
apiVersion: v1
kind: Pod
metadata:
  name: kaniko
spec:
  containers:
  - name: kaniko
    image: registry.cn-hangzhou.aliyuncs.com/weiyigeek/kaniko-executor:latest
    env:
    - name: DOCKERHUB
      value: "docker.io"
    - name: AUTHOR
      value: "weiyigeek"
    - name: IMAGE_NAME
      value: "kaniko-executor"
    - name: IMAGE_VERSION
      value: "v1.9.0"
    args: [ "--dockerfile=/workspace/dockerfile",
            "--context=dir://workspace",
            "--destination=docker.io/weiyigeek/kaniko-executor:v1.9.0",
            "--cache",
            "--cache-dir=/cache"]
    volumeMounts:
      - name: kaniko-secret
        mountPath: /kaniko/.docker
      - name: dockerfile-storage
        mountPath: /workspace
      - name: kaniko-cache
        mountPath: /cache
  restartPolicy: Never
  nodeSelector:
    kubernetes.io/hostname: "weiyigeek-226"
  volumes:
    - name: kaniko-secret
      secret:
        secretName: dockerhub
        items:
          - key: .dockerconfigjson
            path: config.json
    - name: dockerfile-storage
      hostPath:
        path: /storage/dev/soft/kaniko/demo
        type: DirectoryOrCreate
    - name: kaniko-cache
      hostPath:
        path: /storage/dev/soft/kaniko/cache
        type: DirectoryOrCreate
EOF

# args 參數說明
--dockerfile=/workspace/dockerfile   # 指定 dockerfile 路徑
--context=dir://workspace            # 指定構建上下文
--destination=docker.io/weiyigeek/kaniko-executor:v1.9.0  # 指定生成鏡像的tag
--cache     # 使用快取
--cache-dir # 指定快取目錄

溫馨提示: kaniko 中的二進位可執行文件 executor 支援的參數詳解(//github.com/GoogleContainerTools/kaniko/#additional-flags)

步驟 05.執行 kubectl apply 部署資源清單生成運行 pod , 此處通過 kubectl logs 日誌命令可以發現kaniko執行鏡像構建,以及上傳鏡像到docker hub之中

kubectl apply -f kaniko.yaml
# pod/kaniko created

kubectl logs -f kaniko
# INFO[0005] Retrieving image manifest registry.cn-hangzhou.aliyuncs.com/weiyigeek/kaniko-executor:latest
# INFO[0005] Retrieving image registry.cn-hangzhou.aliyuncs.com/weiyigeek/kaniko-executor:latest from registry registry.cn-hangzhou.aliyuncs.com
# INFO[0006] Built cross stage deps: map[]
# INFO[0006] Retrieving image manifest registry.cn-hangzhou.aliyuncs.com/weiyigeek/kaniko-executor:latest
# INFO[0006] Returning cached image manifest
# INFO[0006] Executing 0 build triggers
# INFO[0006] Building stage 'registry.cn-hangzhou.aliyuncs.com/weiyigeek/kaniko-executor:latest' [idx: '0', base-idx: '-1']
# INFO[0006] Skipping unpacking as no commands require it.
# INFO[0006] LABEL [email protected] BUILDTYPE=kaniko
# INFO[0006] Applying label [email protected]
# INFO[0006] Applying label BUILDTYPE=kaniko
# INFO[0006] Pushing image to docker.io/weiyigeek/kaniko-executor:v1.9.0

步驟 06.在客戶端中可以使用 docker 或者 ctr 、crictl 命令將上傳到hub中的鏡像進行拉取, 並且查看hub倉庫中的 kaniko-executor:v1.9.0 鏡像資訊(//hub.docker.com/r/weiyigeek/kaniko-executor)。

docker pull weiyigeek/kaniko-executor:v1.9.0
9d4299bbd943: Already exists
..............
a8dae3110e38: Already exists
v1.9.0: Pulling from weiyigeek/kaniko-executor
Digest: sha256:9b0ef02e7650d00d24bbca683e317bc103d6d842311ff13ec6daee60c37b1e62
Status: Downloaded newer image for weiyigeek/kaniko-executor:v1.9.0
docker.io/weiyigeek/kaniko-executor:v1.9.0

WeiyiGeek.K8S集群中kaniko-executor

步驟 07.擴展補充,除了上述方式指定dockerfile文件和上下文外,我們還可以在運行 kaniko 時使用標準輸入構建上下文,但需要添加 -i, --interactive參數, 一旦kaniko運行它將從STDIN獲取數據,並將構建上下文創建為壓縮tar,然後它將在啟動映像構建之前解包構建上下文的壓縮tar。

如何使用 .tar.gz 標準輸入數據交互運行 kaniko 的完整示例,使用帶有臨時容器和完全無 docker 環境的 Kubernetes 命令行來進行鏡像構建與發布:

echo -e 'FROM alpine \nRUN echo "created from standard input"' > Dockerfile | tar -cf - Dockerfile | gzip -9 | kubectl run kaniko-executor \
--rm --stdin=true \
--image=registry.cn-hangzhou.aliyuncs.com/weiyigeek/kaniko-executor:latest --restart=Never \
--overrides='{
  "apiVersion": "v1",
  "spec": {
    "containers": [
      {
        "name": "kaniko-executor",
        "image": "registry.cn-hangzhou.aliyuncs.com/weiyigeek/kaniko-executor:latest",
        "stdin": true,
        "stdinOnce": true,
        "args": [
          "--dockerfile=Dockerfile",
          "--context=tar://stdin",
          "--destination=docker.io/weiyigeek/alpine:v4.2"
        ],
        "volumeMounts": [
          {
            "name": "kaniko-secret",
            "mountPath": "/kaniko/.docker/"
          }
        ]
      }
    ],
    "nodeSelector": { 
      "kubernetes.io/hostname": "weiyigeek-226"
    },
    "volumes": [
      {
        "name": "kaniko-secret",
        "secret": {
          "secretName": "dockerhub",
          "items": [{"key":".dockerconfigjson", "path": "config.json"}]
        }
      },
      {
        "name": "dockerfile-storage",
        "hostPath": {
          "path": "/storage/dev/soft/kaniko/demo",
          "type": "DirectoryOrCreate"
        }
      },
      {
        "name": "kaniko-cache",
        "hostPath": {
          "path": "/storage/dev/soft/kaniko/cache",
          "type": "DirectoryOrCreate"
        }
      }
    ]
  }
}'

執行結果:

INFO[0003] Retrieving image manifest alpine
INFO[0003] Retrieving image alpine from registry index.docker.io
INFO[0009] Built cross stage deps: map[]
INFO[0009] Retrieving image manifest alpine
INFO[0009] Returning cached image manifest
INFO[0009] Executing 0 build triggers
INFO[0009] Building stage 'alpine' [idx: '0', base-idx: '-1']
INFO[0009] Unpacking rootfs as cmd RUN echo "created from standard input" requires it.
INFO[0036] RUN echo "created from standard input"
INFO[0036] Initializing snapshotter ...
INFO[0036] Taking snapshot of full filesystem...
INFO[0036] Cmd: /bin/sh
INFO[0036] Args: [-c echo "created from standard input"]
INFO[0036] Running: [/bin/sh -c echo "created from standard input"]
created from standard input
INFO[0036] Taking snapshot of full filesystem...
INFO[0037] No files were changed, appending empty layer to config. No layer added to image.
INFO[0037] Pushing image to docker.io/weiyigeek/alpine:v4.2
INFO[0042] Pushed index.docker.io/weiyigeek/alpine@sha256:0ef53bcc0a6f261124e5f292fa17041d7e5f81f5542802b89c249351597167e4
pod "kaniko-executor" deleted

至此在 K8s 集群中使用 kaniko 構建鏡像簡單演示結束。

小試牛刀之在Containerd.io中構建並發布鏡像

描述:當我們的環境中只安裝了containerd.io 容器運行時沒有 Docker 或者 Kubernetes 環境時,我們也可以採用kaniko進行鏡像構建與發布,具體操作流程步驟如下:

環境說明

$ lsb_release -a
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.3 LTS
Release:        20.04
Codename:       focal

$ containerd -v
containerd containerd.io 1.4.12 7b11cfaabd73bb80907dd23182b9347b4245eb5d

$ ctr -v
ctr containerd.io 1.4.12

溫馨提示: 此處使用的是 Ubuntu 20.04 作業系統, 該系統已做安全加固和內核優化符合等保2.0要求【SecOpsDev/Ubuntu-InitializeSecurity.sh at master · WeiyiGeek/SecOpsDev 】, 如你的Linux未進行相應配置環境可能與讀者有些許差異, 如需要進行(windows server、Ubuntu、CentOS)安全加固請參照如下加固腳本進行加固, 請大家瘋狂的star
加固腳本地址:【 //github.com/WeiyiGeek/SecOpsDev/blob/master/OS-作業系統/Linux/Ubuntu/Ubuntu-InitializeSecurity.sh

溫馨提示:如果你使用的是最新 Ubuntu 22.04 作業系統,並需要對其安全加固和內核優化以滿足等保2.0要求可參考如下加固腳本 【//github.com/WeiyiGeek/SecOpsDev/tree/master/OperatingSystem/Security/Ubuntu】。

Ubuntu 22.04加固腳本示例圖

操作流程

步驟 01.此處假設你已經安裝配置好containerd.io了,如果沒有安裝配置請參考此篇文章【 1.Containerd容器運行時初識與嘗試 – //blog.weiyigeek.top/2021/6-27-570.html 】,此處不再累述。

步驟 02.驗證 containerd.io 服務狀態以及提前拉取 kaniko-executor:latest 鏡像以加快構建速度,此處將鏡像拉到默認的名稱空間下。

$ systemctl status containerd.service
● containerd.service - containerd container runtime
     Loaded: loaded (/lib/systemd/system/containerd.service; enabled; vendor preset: enabled)
     Active: active (running) since Thu 2022-09-08 11:48:30 CST; 4h 49min ago
       Docs: //containerd.io
    Process: 561811 ExecStartPre=/sbin/modprobe overlay (code=exited, status=0/SUCCESS)
   Main PID: 561812 (containerd)
      Tasks: 106
     Memory: 4.0G

$ ctr -n default images pull registry.cn-hangzhou.aliyuncs.com/weiyigeek/kaniko-executor:latest

步驟 03.準備登錄 hub docker 的帳號以及密碼,你可以按照下述的流程進行生成config.json文件。

mkdir /storage/dev/soft/kaniko/{config,demo1}
cd /storage/dev/soft/kaniko/config
# 生成認證所需的憑據
# BASE64 編碼,注意下述為格式為 你的hub帳號:你的hub密碼
AUTH=$(echo -n "weiyigeek:password" | base64)
# BASE64 解碼
echo ${AUTH} | base64 -d
# 使用該方法可以解析變數 AUTH (值得注意)
cat > config.json <<EOF
{
  "auths": {
    "//index.docker.io/v1/": {
        "auth": "${AUTH}"
    }
  }
}
EOF

# 生成結果
cat config.json
{
  "auths": {
    "//index.docker.io/v1/": {
        "auth": "d2VpeWlnZ************AxOQ=="
    }
  }
}

步驟 04.準備dockerfile文件,此處將busybox:1.35.0鏡像重新構建後上傳到我的賬戶下的hub倉庫中,該文件示例如下:

cd /storage/dev/soft/kaniko/demo1
tee dockerfile <<'EOF'
FROM docker.io/library/busybox:1.35.0
LABEL [email protected] BUILDTOOLS=kaniko BUILDENV=containerd.io;
ENTRYPOINT ["/bin/sh", "-c", "echo hello,busybox"]
EOF

步驟 05.當上述都準備完成後我們便可以執行containerd.io提供的ctr客戶端工具直接創建容器,例如如下命令:

ctr -n default run --rm --net-host --env DOCKERHUB=docker.io \
--mount type=bind,src=/storage/dev/soft/kaniko/config,dst=/kaniko/.docker,options=rbind:ro \
--mount type=bind,src=/storage/dev/soft/kaniko/demo1,dst=/workspace,options=rbind:rw \
registry.cn-hangzhou.aliyuncs.com/weiyigeek/kaniko-executor:latest kaniko-executor \
/kaniko/executor --dockerfile=/workspace/dockerfile --context=dir://workspace --destination=docker.io/weiyigeek/busybox:1.35.0

# 參數說明
-n 指定名稱空間
--rm 在退出容器時刪除容器
--net-host 使用主機網路
--env 指定容器內部shell變數
--mount 指定掛載到容器內部的本地文件,src是指定宿主機上文件目錄路徑,而dst是指定容器內部目錄。

執行結果:

INFO[0002] Retrieving image manifest docker.io/library/busybox:1.35.0
INFO[0002] Retrieving image docker.io/library/busybox:1.35.0 from registry index.docker.io
INFO[0006] Built cross stage deps: map[]
INFO[0006] Retrieving image manifest docker.io/library/busybox:1.35.0
INFO[0006] Returning cached image manifest
INFO[0006] Executing 0 build triggers
INFO[0006] Building stage 'docker.io/library/busybox:1.35.0' [idx: '0', base-idx: '-1']
INFO[0006] Skipping unpacking as no commands require it.
INFO[0006] LABEL [email protected] BUILDTOOLS=kaniko BUILDENV=containerd.io;
INFO[0006] Applying label [email protected]
INFO[0006] Applying label BUILDTOOLS=kaniko
INFO[0006] Applying label BUILDENV=containerd.io;
INFO[0006] ENTRYPOINT ["/bin/sh", "-c", "echo hello,busybox"]
INFO[0006] Pushing image to docker.io/weiyigeek/busybox:1.35.0
INFO[0010] Pushed index.docker.io/weiyigeek/busybox@sha256:d6ed480cc7864b9e19b40f09263abfad4689a9244a5abeb2e3eaf14a439cc55f

步驟 06.查看上傳到docker hub中 的 busybox:1.35.0 鏡像資訊以及拉取到本地進行運行測試驗證。

ctr -n default images pull docker.io/weiyigeek/busybox:1.35.0
ctr -n default run --rm docker.io/weiyigeek/busybox:1.35.0 busybox
hello,busybox

WeiyiGeek.在containerd.io進行鏡像構建並發布到hub中

至此,在containerd.io 環境中,進行鏡像構建並發布到hub中實踐完畢!

小試牛刀之在Docker中使用kaniko構建並發布鏡像

描述:前面說到kaniko的出現實際是為了在沒有docker環境的情況之下,按照 Dockerfile 文件中的指令進行鏡像構建,不過此處還是簡單的介紹一下在docker環境中的使用。 (實際情況中不建議如此多此一舉)

步驟 01.執行如下命令生成 docker hub 認證票據(存儲路徑為 ~/.docker/config.json)以及提前拉取 kaniko 項目中 executor:latest 鏡像。

docker login -u weiyigeek
# Login with your Docker ID to push and pull images from Docker Hub. If you don't have a Docker ID, head over to //hub.docker.com to create one.
# Login Succeeded

docker pull registry.cn-hangzhou.aliyuncs.com/weiyigeek/kaniko-executor:latest

步驟 02.創建 dockerfile 文件其中 FROM 指定 K8S 集群中常用的NFS動態持久卷鏡像,我們將其上傳到 hub 倉庫中的WeiyiGeek賬戶下面。

mkdir /storage/dev/soft/kaniko/demo2
cd /storage/dev/soft/kaniko/demo2
tee dockerfile <<'EOF'
FROM registry.cn-hangzhou.aliyuncs.com/weiyigeek/nfs-subdir-external-provisioner:latest
LABEL [email protected] BUILDTOOLS=kaniko BUILDENV=docker;
EOF

步驟 03.使用如下示例命令進行 kaniko-executor 容器的創建運行,並進行鏡像構建並上傳到公共的docker hub 倉庫中。

docker rm -f kaniko-executor
docker run --rm --name kaniko-executor \
    -v $HOME/.docker/:/kaniko/.docker \
    -v /storage/dev/soft/kaniko/demo2:/workspace \
    registry.cn-hangzhou.aliyuncs.com/weiyigeek/kaniko-executor:latest \
    --dockerfile=/workspace/dockerfile --context=dir://workspace --destination=docker.io/weiyigeek/nfs-subdir-external-provisioner:latest

執行結果:

INFO[0002] Retrieving image manifest registry.cn-hangzhou.aliyuncs.com/weiyigeek/nfs-subdir-external-provisioner:latest
INFO[0002] Retrieving image registry.cn-hangzhou.aliyuncs.com/weiyigeek/nfs-subdir-external-provisioner:latest from registry registry.cn-hangzhou.aliyuncs.com
INFO[0003] Built cross stage deps: map[]
INFO[0003] Retrieving image manifest registry.cn-hangzhou.aliyuncs.com/weiyigeek/nfs-subdir-external-provisioner:latest
INFO[0003] Returning cached image manifest
INFO[0003] Executing 0 build triggers
INFO[0003] Building stage 'registry.cn-hangzhou.aliyuncs.com/weiyigeek/nfs-subdir-external-provisioner:latest' [idx: '0', base-idx: '-1']
INFO[0003] Skipping unpacking as no commands require it.
INFO[0003] LABEL [email protected] BUILDTOOLS=kaniko BUILDENV=docker;
INFO[0003] Applying label [email protected]
INFO[0003] Applying label BUILDTOOLS=kaniko
INFO[0003] Applying label BUILDENV=docker;
INFO[0003] Pushing image to docker.io/weiyigeek/nfs-subdir-external-provisioner:latest
INFO[0012] Pushed index.docker.io/weiyigeek/nfs-subdir-external-provisioner@sha256:4dc0d27b8fa4608c9e2d8a6f2368d2029df32b9b55f96f27a9218a620ea14828

步驟 04.查看上傳到docker hub 倉庫中的 nfs-subdir-external-provisioner:latest 資訊 (//hub.docker.com/r/weiyigeek/nfs-subdir-external-provisioner) 。

WeiyiGeek.在 Docker 中使用 kaniko 進行鏡像構建與發布

步驟 05.當然我們也可以在安裝有docker環境中使用上下文使用標準輸入,並採用docker進行創建kaniko-executor容器,從標準輸入接收dockerfile文件並進行鏡像構建與推送。

mkdir /storage/dev/soft/kaniko/demo3
echo -e 'FROM alpine \nRUN echo "created from standard input"' > Dockerfile | tar -cf - Dockerfile | gzip -9 | docker run \
  --interactive -v /storage/dev/soft/kaniko/demo3:/workspace  -v $HOME/.docker/:/kaniko/.docker \
  registry.cn-hangzhou.aliyuncs.com/weiyigeek/kaniko-executor:latest \
  --context tar://stdin \
  --destination=docker.io/weiyigeek/alpine:4.2

執行結果: 如果在交互運行期間沒有數據管道傳輸,則需要按Ctrl+D自行發送EOF訊號。

INFO[0000] To simulate EOF and exit, press 'Ctrl+D'
INFO[0002] Retrieving image manifest alpine
INFO[0002] Retrieving image alpine from registry index.docker.io
INFO[0005] Built cross stage deps: map[]
INFO[0005] Retrieving image manifest alpine
INFO[0005] Returning cached image manifest
INFO[0005] Executing 0 build triggers
INFO[0005] Building stage 'alpine' [idx: '0', base-idx: '-1']
INFO[0005] Unpacking rootfs as cmd RUN echo "created from standard input" requires it.
INFO[0008] RUN echo "created from standard input"
INFO[0008] Initializing snapshotter ...
INFO[0008] Taking snapshot of full filesystem...
INFO[0008] Cmd: /bin/sh
INFO[0008] Args: [-c echo "created from standard input"]
INFO[0008] Running: [/bin/sh -c echo "created from standard input"]
created from standard input
INFO[0008] Taking snapshot of full filesystem...
INFO[0008] No files were changed, appending empty layer to config. No layer added to image.
INFO[0008] Pushing image to docker.io/weiyigeek/alpine:4.2
INFO[0016] Pushed index.docker.io/weiyigeek/alpine@sha256:49360dc74ecf57ea94fbec9d7a3b5cf59dfba8aa5e60f8802cc6299e668a3e1e

至此,在 Docker 中使用 kaniko 進行鏡像構建與發布實踐完畢。


0x0n 參考來源

項目地址: //github.com/GoogleContainerTools/kaniko
kaniko 影像鏡像倉庫: gcr.io/kaniko-project/executor
kaniko 中國鏡像倉庫源:weiyigeek/kaniko-executor:latest 或者 registry.cn-hangzhou.aliyuncs.com/weiyigeek/kaniko-executor:latest

原文地址: //blog.weiyigeek.top/2022/9-1-684.html

本文至此完畢,更多技術文章,盡情期待下一章節!


WeiyiGeek Blog 個人部落格 – 為了能到遠方,腳下的每一步都不能少 】

歡迎各位志同道合的朋友一起學習交流【點擊加入交流群】,如文章有誤請在下方留下您寶貴的經驗知識!

作者主頁: 【 //weiyigeek.top
部落格地址: 【 //blog.weiyigeek.top 】

WeiyiGeek Blog 部落格 - 為了能到遠方,腳下的每一步都不能少

專欄書寫不易,如果您覺得這個專欄還不錯的,請給這篇專欄 【點個贊、投個幣、收個藏、關個注,轉個發,留個言】(人間六大情),這將對我的肯定,謝謝!。

  • echo “【點個贊】,動動你那粗壯的拇指或者芊芊玉手,親!”

  • printf(“%s”, “【投個幣】,萬水千山總是情,投個硬幣行不行,親!”)

  • fmt.Printf(“【收個藏】,閱後即焚不吃灰,親!”)

  • console.info(“【轉個發】,讓更多的志同道合的朋友一起學習交流,親!”)

  • System.out.println(“【關個注】,後續瀏覽查看不迷路喲,親!”)

  • cout << “【留個言】,文章寫得好不好、有沒有錯誤,一定要留言喲,親! ” << endl;

//blog.weiyigeek.top

更多網路安全、系統運維、應用開發、物聯網實踐、網路工程、全棧文章,盡在 //blog.weiyigeek.top 之中,謝謝各位看又支援!