kubernetes系列教程(五)初識核心概念pod

寫在前面

前面的系列文章已介紹kubernetes架構,安裝,升級和快速入門,讀者通過文章的實操已對kubernetes已有初步的認識和理解,從本章開始逐步介紹kubernetes中的基礎概念概念和核心概念,基礎概念包括:namespace,labels,annotations,pods,volumes等;核心概念包含kubernetes中各種controller,包含以下幾種:

  • 應用副本控制器有:Deployments,ReplicaSets,DaemonSets,StatefulSets;
  • 批處理任務控制器Jobs和CronJob
  • 存儲控制器PersistentVoloume,PersistentVolumeClaim,StorageClass;
  • 服務負載均衡Service,Ingress,NetworkPolicy和DNS名稱解析;
  • 配置和密鑰ConfigMaps和Secrets

    本文從最基礎的概念pod開始講解,後續逐步介紹應用部署,存儲,負載均衡等相關的控制器,kubernetes內部由多個不同的控制器組成,每個控制器完成不同的功能。

1. 深入學習pod

1.1 Container介紹

容器是一種便攜式,輕量級別的容器虛擬化技術,使用linux cggroup技術實現各種資源的隔離,如cpu,memory,pid,mount,IPC等,相比於虛擬化技術如KVM,容器技術更加輕量級,它的產生主要解決環境的環境發佈的問題,目前主流的容器技術是docker,說到容器,一般都等同於docker。

要運行容器首先需要有鏡像,應用和應用依賴的環境運行在容器中,在kubernetes中不會直接運行container,而是運行pod,一個pod裏面包含多個container,container之間共享相同的namespace,network,storage等。鏡像存儲在私有鏡像或者公有鏡像中,運行時通過docker image pull的方式拉取到本地運行,images的拉取策略包含有兩種:

  • ImagePullPolicy爲Always,不管本地是否有直接下載
  • ImagePullPolicy爲IfNotPresent,默認鏡像拉取得策略,本地不存在再拉取

1.2 Pod概念介紹

Pods是kubernetes中最小的調度單位,Pods內運行一個或者多個container,container之間共享pod的網絡ip資源,存儲volume資源,計算等資源,方便pod內部的container之間能夠實現快速的訪問和交互。

Pod概念介紹

如上圖所示,Pod的使用方式通常包含兩種:

  • Pod中運行一個容器,最經常使用的模式,container封裝在pod中調度,兩者幾乎等同,但k8s不直接管理容器
  • Pod中運行多個容器,多個容器封裝在pod中一起調度,適用於容器之間有數據交互和調用的場景,如app+redis,pod內部共享相同的網絡命名空間,存儲命名空間,進程命名空間等。

1.3 如何創建pod

kubernetes中通過定義生申明式的方式定義資源,即通過在yaml文件中定義所需的資源,kubernetes通過controller-manager按照yaml文件中定義的資源去生成所需的資源(match the current state to desired state)。通常在kubernetes中通過yaml文件的方式定義資源,然後通過kubectl create -f 文件.yaml的方式應用配置,如下演示創建一個nginx應用的操作。

1、編寫yaml文件,定義一個pod資源

[root@node-1 demo]# cat nginx.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: nginx-demo
  labels:
    name: nginx-demo
spec:
  containers:
  - name: nginx-demo
    image: nginx:1.7.9
    imagePullPolicy: IfNotPresent
    ports:
    - name: nginx-port-80
      protocol: TCP
      containerPort: 80

關於配置文件,說明如下:

  • apiVersion api使用的版本,kubectl api-versions可查看到當前系統能支持的版本列表
  • kind 指定資源類型,表示爲Pod的資源類型
  • metadata 指定Pod的元數據,metadata.name指定名稱,metadata.labels指定Pod的所屬的標籤
  • spec 指定Pod的模版屬性,spec.containers配置容器的信息,spec.containers.name指定名字,spec.containers.image指定容器鏡像的名稱,spec.containers.imagePullPolicy是鏡像的下載方式,IfNotPresent表示當鏡像不存在時下載,spec.containers.ports.name指定port的名稱,spec.containers.ports.protocol協議類型爲TCP,spec.containers.ports.containerPort爲容器端口。

2、創建pod應用

[root@node-1 demo]# kubectl apply -f nginx.yaml 
pod/nginx-demo created

3、訪問應用

獲取容器的IP地址
[root@node-1 demo]# kubectl get pods -o wide 
NAME                    READY   STATUS    RESTARTS   AGE   IP            NODE     NOMINATED NODE   READINESS GATES
demo-7b86696648-8bq7h   1/1     Running   0          8h    10.244.1.11   node-2   <none>           <none>
demo-7b86696648-8qp46   1/1     Running   0          8h    10.244.1.10   node-2   <none>           <none>
demo-7b86696648-d6hfw   1/1     Running   0          8h    10.244.1.12   node-2   <none>           <none>
nginx-demo              1/1     Running   0          50s   10.244.2.11   node-3   <none>           <none>

訪問站點內容:
[root@node-1 demo]# curl http://10.244.2.11
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

前面我們我們學習過kubernetes支持滾動升級RollingUpdate,彈性擴容replicas等特性,如何給Pod做滾動升級保障業務不中斷,如何提高Pod的副本個數保障高可用呢?答案是:不支持。Pod是單個,無法支持一些高級特性,高級特性需要通過高級的副本控制器如ReplicaSets,Deployments,StatefulSets,DaemonSets等才能支持。Pod在實際應用中很少用,除了測試和運行一些簡單的功能外,實際使用建議使用Deployments代替,Pod的定義以Template的方式嵌入在副本控制器中。

2. 如何編寫yaml文件

前面我們提到過kubernetse是申明式的方式部署應用,應用的部署都定義在yaml文件中來實現,如何來編寫應用的yaml文件呢,下面我來分享兩個世紀使用的技巧:

1、通過定義模版快速生成,kubectl create apps -o yaml --dry-run的方式生成,--dry-run僅僅是試運行,並不實際在k8s集羣中運行,通過指定-o yaml輸出yaml格式文件,生成後給基於模版修改即可,如下:

[root@node-1 demo]# kubectl create deployment demo --image=nginx:latest  --dry-run -o yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  creationTimestamp: null
  labels:
    app: demo
  name: demo
spec:
  replicas: 1
  selector:
    matchLabels:
      app: demo
  strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: demo
    spec:
      containers:
      - image: nginx:latest
        name: nginx
        resources: {}
status: {}

2、explain命令,explain命令堪稱是語法查詢器,可以查到每個字段的含義,使用說明和使用方式,如想要查看Pod的spec中containers其他支持的字段,可以通過kubectl explain Pod.spec.containers的方式查詢,如下:

[root@node-1 demo]# kubectl explain Pods.spec.containers
KIND:     Pod
VERSION:  v1

RESOURCE: containers <[]Object>

DESCRIPTION:
     List of containers belonging to the pod. Containers cannot currently be
     added or removed. There must be at least one container in a Pod. Cannot be
     updated.

     A single application container that you want to run within a pod.

FIELDS:
   args <[]string> #命令參數
     Arguments to the entrypoint. The docker image's CMD is used if this is not
     provided. Variable references $(VAR_NAME) are expanded using the
     container's environment. If a variable cannot be resolved, the reference in
     the input string will be unchanged. The $(VAR_NAME) syntax can be escaped
     with a double $$, ie: $$(VAR_NAME). Escaped references will never be
     expanded, regardless of whether the variable exists or not. Cannot be
     updated. More info:
     https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell

   image    <string> #鏡像定義
     Docker image name. More info:
     https://kubernetes.io/docs/concepts/containers/images This field is
     optional to allow higher level config management to default or override
     container images in workload controllers like Deployments and StatefulSets.

   ports    <[]Object> #端口定義
     List of ports to expose from the container. Exposing a port here gives the
     system additional information about the network connections a container
     uses, but is primarily informational. Not specifying a port here DOES NOT
     prevent that port from being exposed. Any port which is listening on the
     default "0.0.0.0" address inside a container will be accessible from the
     network. Cannot be updated.

   readinessProbe   <Object> #可用健康檢查
     Periodic probe of container service readiness. Container will be removed
     from service endpoints if the probe fails. Cannot be updated. More info:
     https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes

   resources    <Object> #資源設置
     Compute Resources required by this container. Cannot be updated. More info:
     https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/

...省略部分輸出...
   volumeMounts <[]Object> #掛載存儲
     Pod volumes to mount into the container's filesystem. Cannot be updated.

   workingDir   <string>
     Container's working directory. If not specified, the container runtime's
     default will be used, which might be configured in the container image.
     Cannot be updated.

關於explain內容解釋說明

  • <string> 表示後面接一個字符串
  • <[]Object> 表示後面是一個列表的對象,列表需要以-開始,且可以寫多個
  • <Object> 表示一個對象,對象內部包含多個屬性

如繼續上面的內容,如果需要查看resource資源定義,可以通過explain pods.spec.containers.resource來查看具體的使用方法。

通過上面兩個工具的介紹,平時在日常工作中找到編寫yaml文件部署應用的地圖,建議手工多寫幾次,注意語法鎖進,多寫幾次就熟悉了。Pod中設計到有很多的特性,如資源分配,健康檢查,存儲掛載等(參考附錄文章),後續我們做詳細介紹,Pod將以Template的方式嵌入到副本控制器如Deployments中。

4. 附錄

容器鏡像介紹:https://kubernetes.io/docs/concepts/containers/images/

Pod介紹:https://kubernetes.io/docs/concepts/workloads/pods/pod-overview/

Resource限定內存資源:https://kubernetes.io/docs/tasks/configure-pod-container/assign-memory-resource/

Resource限定CPU資源:https://kubernetes.io/docs/tasks/configure-pod-container/assign-cpu-resource/

Pod掛載存儲:https://kubernetes.io/docs/tasks/configure-pod-container/configure-volume-storage/

Pod配置健康檢查:https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/


當你的才華撐不起你的野心時,你就應該靜下心來學習

返回kubernetes系列教程目錄

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章