# Kubernetes 超入門

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

### Pod&#x20;

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

![](https://853423727-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZBn9owI5fBe0HrECdk%2Fuploads%2FEyVzIGNnLKmsekSw1mmw%2Fimage.png?alt=media\&token=ee6286da-0b7c-4094-b749-3e992ddbb38d)

{% hint style="info" %}
Pod 可以想成 group of container
{% endhint %}

#### 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 範例。

```yaml
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***

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

**step 1.安裝k3s**

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

**step 2.執行demo.yml 檔案**

```shell
sudo kubectl apply -f demo.yml
```

**step 3.取得status**

```shell
sudo kubectl get pod/nginx-demo -o yaml
```

![status example](https://853423727-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MZBn9owI5fBe0HrECdk%2Fuploads%2FE6KSUyXFiRfQ5tb6Erm5%2Fimage.png?alt=media\&token=9b675d43-fae5-4305-94a5-969289f4a3f2)

### 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/>
