Kubernetes 超入門

Kubernetes(k8s) 是一種讓使用者管理Cluster 的一種工具,在各雲端平台如Azure, GKE, AWS...等等都支援,本文章提供kubernetes 基礎觀念。

Kubernetes 是一種讓使用者管理Cluster 的一種工具,能更輕鬆的管理node。本身提供Service Discovery 與 load-balance 的功能,像是自動配置IP等等。此外也提供進一步的操作,如設定記憶體限制、資料映射的區域等等。但更重要的事情是提供Self-healingAutomated rollouts and rollbacks,讓正在運行的node 可以自動的上下線,甚至可以自行修復node。

Pod

是在kubernetes 中最小單位,一個Pod指的是一個小的服務集,換句話說Pod 包含許多的container即微服務,但一個pod 不代表是一個Node。若是對比 docker 生態系,Pod 類似 docker-compose,可設定記憶體配置、mount disk 、cpu 數量等等,且都是透過yaml檔案進行設置。

Pod 可以想成 group of container

Pod ymal 設定

Pod ymal 檔案主要有幾個必填項目[1]:

  • apiVersion - Which version of the Kubernetes API you're using to create this object

  • kind - What kind of object you want to create

  • metadata - Data that helps uniquely identify the object, including a name string, UID, and optional namespace

  • spec - What state you desire for the object

那一般來說一個Pod 的設定檔會包含兩個Object, spec、status這兩個Object,spec 主要是定義Pod 有哪些container運行與設定,status主要是提供Pod狀態讓 controller (control plane)去更新、撤銷[2]。換句話說spec 是在 yaml 檔案進行設定Pod的狀態,然而status則是需透過 api或者cmd的方式讀取目前Pod 的狀態。

例如下列 nginx 範例。

apiVersion: v1
kind: Pod
metadata:
  name: nginx-demo
spec:
  containers:
  - name: nginx
    image: nginx:1.14.2
    ports:
    - containerPort: 80

範例實作

由於k8s 本身的硬體需求比較龐大,因此各家機構紛紛推出自己的k8s開放工具,如Ubuntu基金會的Micro-K8s 或者 Rancher 的 k3s...等等,本範例使用k3s 進行解說,測試環境作業系統為ubuntu 20.04。

Pod ymal 檔案主要有幾個必填項目:

  • apiVersion - Which version of the Kubernetes API you're using to create this object

  • kind - What kind of object you want to create

  • metadata - Data that helps uniquely identify the object, including a name string, UID, and optional namespace

  • spec - What state you desire for the object

Attachment demo.yml

apiVersion: v1
kind: Pod
metadata:
  name: nginx-demo
spec:
  containers:
  - name: nginx
    image: nginx:1.14.2
    ports:
    - containerPort: 80

step 1.安裝k3s

// install k3s
curl -sfL https://get.k3s.io | INSTALL_K3S_CHANNEL=latest sh -

step 2.執行demo.yml 檔案

sudo kubectl apply -f demo.yml

step 3.取得status

sudo kubectl get pod/nginx-demo -o yaml

Reference

[1] https://kubernetes.io/docs/home/ [2] https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status [3] https://rancher.com/docs/k3s/latest/

Last updated