網頁

2023/12/29

Kubernates 使用Deployment部署應用程式

本篇參考官方教學Using kubectl to Create a Deployment進行操作。


範例環境:

  • MacBook Pro Apple M1 Pro (ARM64)
  • macOS Ventura 13.0.1
  • Docker Desktop 4.21.1


事前要求

參考「Mac ARM64 Kubernetes minikube安裝」以Homebrew安裝minikube。


建立Cluster

開啟終端機,輸入minikube start建立minikube cluster。

% minikube start
😄  minikube v1.32.0 on Darwin 13.0.1 (arm64)
✨  Using the docker driver based on existing profile
👍  Starting control plane node minikube in cluster minikube
🚜  Pulling base image ...
🔄  Restarting existing docker container for "minikube" ...
🐳  Preparing Kubernetes v1.28.3 on Docker 24.0.7 ...
🔗  Configuring bridge CNI (Container Networking Interface) ...
🔎  Verifying Kubernetes components...
    ▪ Using image docker.io/kubernetesui/dashboard:v2.7.0
    ▪ Using image gcr.io/k8s-minikube/storage-provisioner:v5
    ▪ Using image docker.io/kubernetesui/metrics-scraper:v1.0.8
💡  Some dashboard features require the metrics-server addon. To enable all features please run:

	minikube addons enable metrics-server


🌟  Enabled addons: storage-provisioner, default-storageclass, dashboard
🏄  Done! kubectl is now configured to use "minikube" cluster and "default" namespace by default


建立Deployment

在終端機輸入kubectl create deployment kubernetes-bootcamp --image=gcr.io/google-samples/kubernetes-bootcamp:v1建立一個Deployment kubernetes-bootcamp來在Pods的容器中運行一個指定的image gcr.io/google-samples/kubernetes-bootcamp:v1

% kubectl create deployment kubernetes-bootcamp --image=gcr.io/google-samples/kubernetes-bootcamp:v1
deployment.apps/kubernetes-bootcamp created


檢視Deployment

輸入kubectl get deployments檢視Deployment。

% kubectl get deployments
NAME                  READY   UP-TO-DATE   AVAILABLE   AGE
kubernetes-bootcamp   1/1     1            1           12s


檢視Pods

輸入kubectl get pods檢視Pods清單。可以看到一個運行的Pod名稱為kubernetes-bootcamp-f95c5b745-ckkdz

% kubectl get pods
NAME                                  READY   STATUS    RESTARTS   AGE
kubernetes-bootcamp-f95c5b745-ckkdz   1/1     Running   0          55s

輸入kubectl describe pods <POD_NAME>,檢視Pod詳細資訊,<POD_NAME>為Pod名稱。

% kubectl describe pods kubernetes-bootcamp-f95c5b745-ckkdz
Name:             kubernetes-bootcamp-f95c5b745-ckkdz
Namespace:        default
Priority:         0
Service Account:  default
Node:             minikube/192.168.49.2
Start Time:       Fri, 29 Dec 2023 17:02:20 +0800
Labels:           app=kubernetes-bootcamp
                  pod-template-hash=f95c5b745
Annotations:      <none>
Status:           Running
IP:               10.244.0.9
IPs:
  IP:           10.244.0.9
Controlled By:  ReplicaSet/kubernetes-bootcamp-f95c5b745
Containers:
  kubernetes-bootcamp:
    Container ID:   docker://34879d22314d40c087c21558114fd24d4eba1f7b4ceea5a1fdfeae77b5fe76b4
    Image:          gcr.io/google-samples/kubernetes-bootcamp:v1
    Image ID:       docker-pullable://gcr.io/google-samples/kubernetes-bootcamp@sha256:0d6b8ee63bb57c5f5b6156f446b3bc3b3c143d233037f3a2f00e279c8fcc64af
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Fri, 29 Dec 2023 17:02:31 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-q2gmj (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             True
  ContainersReady   True
  PodScheduled      True
Volumes:
  kube-api-access-q2gmj:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
QoS Class:                   BestEffort
Node-Selectors:              <none>
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:                      <none>


查看Pods日誌

輸入kubetl logs <POD_NAME>查看Pod日誌記錄。

% kubectl logs kubernetes-bootcamp-f95c5b745-ckkdz
Kubernetes Bootcamp App Started At: 2023-12-29T09:02:31.752Z | Running On:  kubernetes-bootcamp-f95c5b745-ckkdz

Running On: kubernetes-bootcamp-f95c5b745-ckkdz | Total Requests: 1 | App Uptime: 5009.598 seconds | Log Time: 2023-12-29T10:26:01.350Z


在Pod容器中執行命令

輸入kubectl exec <POD_NAME≫ -- <COMMAND>在Pod容器中執行命令,<COMMAND≫為要執行的命令。

例如輸入kubectl exec kubernetes-bootcamp-f95c5b745-ckkdz -- env在Pod kubernetes-bootcamp-f95c5b745-ckkdz的容器中執行env命令。

% kubectl exec kubernetes-bootcamp-f95c5b745-ckkdz -- env
HOME=/root
NODE_VERSION=6.3.1
NPM_CONFIG_LOGLEVEL=info
KUBERNETES_SERVICE_PORT=443
KUBERNETES_SERVICE_HOST=10.96.0.1
KUBERNETES_PORT_443_TCP_ADDR=10.96.0.1
KUBERNETES_PORT_443_TCP_PORT=443
KUBERNETES_PORT_443_TCP_PROTO=tcp
KUBERNETES_PORT_443_TCP=tcp://10.96.0.1:443
KUBERNETES_PORT=tcp://10.96.0.1:443
KUBERNETES_SERVICE_PORT_HTTPS=443
HOSTNAME=kubernetes-bootcamp-f95c5b745-ckkdz
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin


開啟Pod容器的bash

輸入kubectl exec -ti <POD_NAME> -- bash開啟/進入Pod容器的bash。

% kubectl exec -ti kubernetes-bootcamp-f95c5b745-ckkdz -- bash
root@kubernetes-bootcamp-f95c5b745-ckkdz:/#


開啟proxy

開啟新的終端機,輸入kubectl proxy開啟連接到Kubernates API server的proxy(代理),供本機可以透過proxy存取Kubernates API server,預設使用HTTP port 8001。

% kubectl proxy
Starting to serve on 127.0.0.1:8001


Kubernates API查看Pod資訊

輸入curl http://localhost:8001/api/v1/namespaces/default/pods/kubernetes-bootcamp-f95c5b745-ckkdz,透過curl發送URL到Kubernates API/api/v1/namespaces/default/pods/<POD_NAME>查看Pod kubernetes-bootcamp-f95c5b745-ckkdz的資訊。

% curl http://localhost:8001/api/v1/namespaces/default/pods/kubernetes-bootcamp-f95c5b745-ckkdz
{
  "kind": "Pod",
  "apiVersion": "v1",
  "metadata": {
    "name": "kubernetes-bootcamp-f95c5b745-ckkdz",
    "generateName": "kubernetes-bootcamp-f95c5b745-",
    "namespace": "default",
    "uid": "0d57d35b-8eb6-4658-8f4c-adabb5bb7706",
    "resourceVersion": "8855",
    "creationTimestamp": "2023-12-29T09:02:20Z",
    "labels": {
      "app": "kubernetes-bootcamp",
      "pod-template-hash": "f95c5b745"
    },
    "ownerReferences": [
      {
        "apiVersion": "apps/v1",
        "kind": "ReplicaSet",
        "name": "kubernetes-bootcamp-f95c5b745",
        "uid": "6b03864b-5daf-46b7-a4e6-8eea74502042",
        "controller": true,
        "blockOwnerDeletion": true
      }
    ],
    "managedFields": [
      {
        "manager": "kube-controller-manager",
        "operation": "Update",
        "apiVersion": "v1",
        "time": "2023-12-29T09:02:20Z",
        "fieldsType": "FieldsV1",
        "fieldsV1": {
          "f:metadata": {
            "f:generateName": {},
            "f:labels": {
              ".": {},
              "f:app": {},
              "f:pod-template-hash": {}
            },
            "f:ownerReferences": {
              ".": {},
              "k:{\"uid\":\"6b03864b-5daf-46b7-a4e6-8eea74502042\"}": {}
            }
          },
          "f:spec": {
            "f:containers": {
              "k:{\"name\":\"kubernetes-bootcamp\"}": {
                ".": {},
                "f:image": {},
                "f:imagePullPolicy": {},
                "f:name": {},
                "f:resources": {},
                "f:terminationMessagePath": {},
                "f:terminationMessagePolicy": {}
              }
            },
            "f:dnsPolicy": {},
            "f:enableServiceLinks": {},
            "f:restartPolicy": {},
            "f:schedulerName": {},
            "f:securityContext": {},
            "f:terminationGracePeriodSeconds": {}
          }
        }
      },
      {
        "manager": "kubelet",
        "operation": "Update",
        "apiVersion": "v1",
        "time": "2023-12-29T09:02:31Z",
        "fieldsType": "FieldsV1",
        "fieldsV1": {
          "f:status": {
            "f:conditions": {
              "k:{\"type\":\"ContainersReady\"}": {
                ".": {},
                "f:lastProbeTime": {},
                "f:lastTransitionTime": {},
                "f:status": {},
                "f:type": {}
              },
              "k:{\"type\":\"Initialized\"}": {
                ".": {},
                "f:lastProbeTime": {},
                "f:lastTransitionTime": {},
                "f:status": {},
                "f:type": {}
              },
              "k:{\"type\":\"Ready\"}": {
                ".": {},
                "f:lastProbeTime": {},
                "f:lastTransitionTime": {},
                "f:status": {},
                "f:type": {}
              }
            },
            "f:containerStatuses": {},
            "f:hostIP": {},
            "f:phase": {},
            "f:podIP": {},
            "f:podIPs": {
              ".": {},
              "k:{\"ip\":\"10.244.0.9\"}": {
                ".": {},
                "f:ip": {}
              }
            },
            "f:startTime": {}
          }
        },
        "subresource": "status"
      }
    ]
  },
  "spec": {
    "volumes": [
      {
        "name": "kube-api-access-q2gmj",
        "projected": {
          "sources": [
            {
              "serviceAccountToken": {
                "expirationSeconds": 3607,
                "path": "token"
              }
            },
            {
              "configMap": {
                "name": "kube-root-ca.crt",
                "items": [
                  {
                    "key": "ca.crt",
                    "path": "ca.crt"
                  }
                ]
              }
            },
            {
              "downwardAPI": {
                "items": [
                  {
                    "path": "namespace",
                    "fieldRef": {
                      "apiVersion": "v1",
                      "fieldPath": "metadata.namespace"
                    }
                  }
                ]
              }
            }
          ],
          "defaultMode": 420
        }
      }
    ],
    "containers": [
      {
        "name": "kubernetes-bootcamp",
        "image": "gcr.io/google-samples/kubernetes-bootcamp:v1",
        "resources": {},
        "volumeMounts": [
          {
            "name": "kube-api-access-q2gmj",
            "readOnly": true,
            "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount"
          }
        ],
        "terminationMessagePath": "/dev/termination-log",
        "terminationMessagePolicy": "File",
        "imagePullPolicy": "IfNotPresent"
      }
    ],
    "restartPolicy": "Always",
    "terminationGracePeriodSeconds": 30,
    "dnsPolicy": "ClusterFirst",
    "serviceAccountName": "default",
    "serviceAccount": "default",
    "nodeName": "minikube",
    "securityContext": {},
    "schedulerName": "default-scheduler",
    "tolerations": [
      {
        "key": "node.kubernetes.io/not-ready",
        "operator": "Exists",
        "effect": "NoExecute",
        "tolerationSeconds": 300
      },
      {
        "key": "node.kubernetes.io/unreachable",
        "operator": "Exists",
        "effect": "NoExecute",
        "tolerationSeconds": 300
      }
    ],
    "priority": 0,
    "enableServiceLinks": true,
    "preemptionPolicy": "PreemptLowerPriority"
  },
  "status": {
    "phase": "Running",
    "conditions": [
      {
        "type": "Initialized",
        "status": "True",
        "lastProbeTime": null,
        "lastTransitionTime": "2023-12-29T09:02:20Z"
      },
      {
        "type": "Ready",
        "status": "True",
        "lastProbeTime": null,
        "lastTransitionTime": "2023-12-29T09:02:31Z"
      },
      {
        "type": "ContainersReady",
        "status": "True",
        "lastProbeTime": null,
        "lastTransitionTime": "2023-12-29T09:02:31Z"
      },
      {
        "type": "PodScheduled",
        "status": "True",
        "lastProbeTime": null,
        "lastTransitionTime": "2023-12-29T09:02:20Z"
      }
    ],
    "hostIP": "192.168.49.2",
    "podIP": "10.244.0.9",
    "podIPs": [
      {
        "ip": "10.244.0.9"
      }
    ],
    "startTime": "2023-12-29T09:02:20Z",
    "containerStatuses": [
      {
        "name": "kubernetes-bootcamp",
        "state": {
          "running": {
            "startedAt": "2023-12-29T09:02:31Z"
          }
        },
        "lastState": {},
        "ready": true,
        "restartCount": 0,
        "image": "gcr.io/google-samples/kubernetes-bootcamp:v1",
        "imageID": "docker-pullable://gcr.io/google-samples/kubernetes-bootcamp@sha256:0d6b8ee63bb57c5f5b6156f446b3bc3b3c143d233037f3a2f00e279c8fcc64af",
        "containerID": "docker://34879d22314d40c087c21558114fd24d4eba1f7b4ceea5a1fdfeae77b5fe76b4",
        "started": true
      }
    ],
    "qosClass": "BestEffort"
  }
}


沒有留言:

張貼留言