k8s中文社區文檔:http://docs.kubernetes.org.cn/php
k8s中文社區YAML:https://www.kubernetes.org.cn/1414.htmlhtml
(1).kubectl概述node
kubectl是Kubernetes集羣的命令行工具,經過kubectl可以對集羣自己進行管理,並可以在集羣上進行容器化應用的安裝部署。python
(2).語法說明mysql
語法:kubectl [操做命令] [資源類型] [資源名稱] [可選參數]nginx
操做命令:指對一個或多個資源執行的操做。web
資源類型:資源類型不區分大小寫,可指定單數、複數或縮寫形式。sql
資源名稱:資源名稱區分大小寫,若是省略則顯示全部資源的詳細信息。docker
在指定多個資源執行操做時,能夠按資源類型和資源名稱指定每一個資源,或指定一個或多個模板文件。在按資源類型和資源名稱指定資源時,能夠對同一資源類型的資源進行分類(例如:kubectl get pod example-pod1 example-pod2),也能夠分別指定多個資源類型。在指定一個或多個模板文件時,使用yaml格式而不是json格式,由於yaml格式更易於使用,特別是配置文件。json
可選參數:指定的可選參數會覆蓋默認值和相應的環境變量。
完整內容請看:https://kubernetes.io/zh/docs/reference/kubectl/overview/
(3).yaml語法規則
YAML特別適合用來表達或編輯數據結構、各類配置文件、傾印調試內容、文件大綱(例如:許多電子郵件標題格式和YAML很是接近),YAML 的配置文件後綴爲.yml,例如:example.yml。
1)yaml配置文件常見單詞
kind:類型;apiVersion:API版本;metadata:元數據;spec:規格,說明書(定義具體參數);replicas:副本;selector:選擇器;template:模板;
2)基本語法規則
一、大小寫敏感(區分大小寫);
二、使用縮進表示層級;
三、縮進時不容許使用<Tab>鍵,只能使用空格;
四、縮進空格數目不重要,只要相同層級的元素左對齊便可;
五、#表示註釋;
六、在yaml裏,連續的項目(如:數組元素、集合元素)經過減號"-"來表示,map結構裏的鍵值對(key/value)用冒號":"來分隔。
3)數據結構
YAML支持三種數據結構:對象、數組、純量。
對象:鍵值對的集合,又稱爲映射(mapping)/ 哈希(hashes) / 字典(dictionary)
數組:一組按次序排列的值,又稱爲序列(sequence) / 列表(list)
純量(scalars):單個的、不可再分的值
4)對象
對象的鍵值對使用冒號結構表示[key]: [value],冒號後存在一個空格。例如:
key: value
也能夠將全部鍵值對寫成行內對象,例如:
key: {child-key1: value1,child-key2: value2} 或 key: child-key1: value1 child-key2: value2
較爲複雜的對象格式,能夠用問號加空格表示一個複雜的key開始,用冒號加空格表示一個複雜的value開始。例如:
? - complexkey1 - complexkey2 : - complexvalue1 - complexvalue2
該對象的屬性是一個數組,該對象的值也是一個數組。
5)數組
一組以減號(連詞線)"-"開頭的行構成一個數組。例如:
- A - B - C
支持多維數組,可使用行內表示:
key: [value1,value2,value3...]
若是不想有key,那麼就以下:
- - A - B - C
最後舉一個對象與數組的複雜例子,以下:
OS: - id: 1 name: CentOS version: 7.5 - id: 2 name: Windows version: 7 也能夠寫成流式,以下: OS: [{id: 1,name: CentOS,version: 7.5},{id: 2,name: Windows,version: 7}]
6)複合結構
符合結構就是對象和數組的混合使用,數組中也有一個例子。這裏再寫一個例子,並與json格式進行對比
YAML格式:
languages: - Ruby - Perl - Python websites: YAML: yaml.org Ruby: ruby-lang.org Python: python.org Perl: use.perl.org
JSON格式:
{ languages: [ 'Ruby', 'Perl', 'Python'], websites: { YAML: 'yaml.org', Ruby: 'ruby-lang.org', Python: 'python.org', Perl: 'use.perl.org' } }
7)純量
純量是指最基本的,不可再分的值。包括:字符串、布爾值、整數、浮點數、Null、時間和日期。
一個例子直接帶過,以下:
boolean: - TRUE #true,True均可以 - FALSE #false,False均可以 float: - 3.14 - 6.8523015e+5 #可使用科學計數法 int: - 123 - 0b1010_0111_0100_1010_1110 #二進制表示 null: nodeName: 'node' parent: ~ #使用~表示null string: - 哈哈 - 'Hello world' #可使用雙引號或者單引號包裹字符串 - newline newline2 #字符串能夠拆成多行,換行符會被轉化成一個空格 date: - 2018-02-17 #日期必須使用ISO 8601格式,即yyyy-MM-dd datetime: - 2018-02-17T15:02:31+08:00 #時間使用ISO 8601格式,時間和日期之間使用T鏈接,最後使用+表明時區
8)引用
"& [別名]"創建引用內容,並設置別名;"<<"合併到當前數據;": [別名]"經過別名引用內容。
舉一個較爲複雜的例子:
defaults: &defaults adapter: postgres host: localhost development: database: myapp_development <<: *defaults test: database: myapp_test <<: *defaults
徹底展開,至關於:
defaults: adapter: postgres host: localhost development: database: myapp_development adapter: postgres host: localhost test: database: myapp_test adapter: postgres host: localhost
以爲很差理解的,能夠轉換爲流式進行理解。好比說:
defaults: adapter: postgres host: localhost 等同於: defaults: {adapter: postgres,host: localhost} 那麼 defaults: &defaults adapter: postgres host: localhost 就等同於: defaults: &defaults {adapter: postgres,host: localhost}
是否是更好理解一點呢。
(4).經常使用命令
首先須要在兩臺node節點上配置docker加速器,而後下載一個centos鏡像和一個k8s基礎鏡像(也能夠從本地導入鏡像)。說明:docker.io是指由Ubuntu維護的鏡像。
# tee /etc/docker/daemon.json <<-'EOF' { "registry-mirrors": ["https://8mkqrctt.mirror.aliyuncs.com"] } EOF # systemctl daemon-reload && systemctl restart docker # docker search nginx INDEX NAME DESCRIPTION STARS OFFICIAL AUTOMATED docker.io docker.io/nginx Official build of Nginx. 12501 [OK] docker.io docker.io/jwilder/nginx-proxy Automated Nginx reverse proxy for docker c... 1721 [OK] docker.io docker.io/richarvey/nginx-php-fpm Container running Nginx + PHP-FPM capable ... 753 [OK] ...... # docker pull docker.io/nginx #下載演示用鏡像 Using default tag: latest Trying to pull repository docker.io/library/nginx ... latest: Pulling from docker.io/library/nginx 8ec398bc0356: Pull complete dfb2a46f8c2c: Pull complete b65031b6a2a5: Pull complete Digest: sha256:8aa7f6a9585d908a63e5e418dc5d14ae7467d2e36e1ab4f0d8f9d059a3d071ce Status: Downloaded newer image for docker.io/nginx:latest # docker search registry.access.redhat.com/rhel7/pod-infrastructure #k8s基礎鏡像,能夠提早下載。也可以讓k8s自動下載 INDEX NAME DESCRIPTION STARS OFFICIAL AUTOMATED redhat.com registry.access.redhat.com/rhel7/pod-infrastructure OpenShift Container Platform Infrastructur... 0 # docker pull registry.access.redhat.com/rhel7/pod-infrastructure
注意:若是沒有提早下載registry.access.redhat.com/rhel7/pod-infrastructure這個k8s的基礎鏡像,那麼在建立容器副本時會優先下載該鏡像,而且查看pods狀態時會一直處在ContainerCreating(容器建立中),此時只需等待k8s下載完該鏡像便可。
1)kubectl run運行鏡像實例
kubectl run NAME --image=image [--env="key=value"] [--port=port] [--replicas=replicas] [--dry-run=bool] [--overrides=inline-json] [flags]
說明:--replicas是爲此容器建立的副本數量。
在master上使用kubectl建立鏡像實例,在建立過程當中會自動生成deployment和pod來管理容器。說明:deployment(Deployment controller,部署控制器)爲Pods和ReplicaSets(副本集合)提供聲明性更新,即在部署對象中描述所需的狀態,部署控制器將會在可控範圍內將實際狀態變動爲所需狀態。經過部署控制器能夠建立新的副本,或刪除現有副本,或回收資源從新建立新的副本。
[root@kube-master ~]# kubectl run nginx --image=docker.io/nginx --port=9000 --replicas=1 deployment "nginx" created [root@kube-master ~]# kubectl get deployment NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE nginx 1 1 1 1 5s [root@kube-master ~]# kubectl get pods NAME READY STATUS RESTARTS AGE nginx-2187705812-qhrr1 1/1 Running 0 16s
pods的狀態通常有四種:一、ContainerCreating,容器建立中;二、ImagePullBackOff,從後端(docker鏡像站)把鏡像拉取到本地時斷開,建議本地鏡像或阿里雲加速器;三、Running,正在運行中;四、Terminating,終止,刪除pod時的狀態。
若是一直處在ContainerCreating或Terminating時,請檢查全部node節點是否存在registry.access.redhat.com/rhel7/pod-infrastructure這個k8s基礎鏡像,沒有也不用擔憂,等待k8s下載,就是時間會比較長。
建立完成後能夠到node節點上使用docker命令查看一下,能夠發現只啓動了一個nginx鏡像實例
#node1節點上沒有啓動實例 [root@kube-node1 ~]# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES #node2節點上啓動了 [root@kube-node2 ~]# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 385b564f1765 docker.io/nginx "nginx -g 'daemon ..." 38 minutes ago Up 38 minutes k8s_nginx.92d20176_nginx-2187705812-qhrr1_default_06a3ebf9-3a64-11ea-af25-000c29d2651b_b37ddfc8 ff7ef18731c5 registry.access.redhat.com/rhel7/pod-infrastructure:latest "/usr/bin/pod" 38 minutes ago Up 38 minutes k8s_POD.17af0ba2_nginx-2187705812-qhrr1_default_06a3ebf9-3a64-11ea-af25-000c29d2651b_95f2d0df
2020.2.17補充:namespce、deployment、replicaset、pod四者之間的關係。看幾個獲取信息,應該就很好理解了。
#第一個,獲取四者存在的名稱 [root@kube-master ~]# kubectl get namespace NAME STATUS AGE default Active 33d kube-system Active 33d [root@kube-master ~]# kubectl get deployment NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE nginx 1 1 1 1 27d [root@kube-master ~]# kubectl get replicaset NAME DESIRED CURRENT READY AGE nginx-2187705812 1 1 1 27d [root@kube-master ~]# kubectl get pod NAME READY STATUS RESTARTS AGE nginx-2187705812-cbb2s 1/1 Running 1 27d #第二個,獲取四者的詳細信息 [root@kube-master ~]# kubectl describe pod nginx-2187705812-cbb2s Name: nginx-2187705812-cbb2s #pod的名稱 Namespace: default #所屬命名空間 Node: kube-node2/192.168.128.112 Start Time: Mon, 20 Jan 2020 13:14:29 +0800 Labels: pod-template-hash=2187705812 run=nginx Status: Running IP: 10.255.21.2 Controllers: ReplicaSet/nginx-2187705812 #所屬的副本控制器(新版本中的名稱,RC變爲RS) Containers: nginx: Container ID: docker://4a15ef334ee88704a182982ea5d7b241b0b76f5a5df293660828696c3c71eb75 Image: docker.io/nginx Image ID: docker-pullable://docker.io/nginx@sha256:ad5552c786f128e389a0263104ae39f3d3c7895579d45ae716f528185b36bc6f Port: 9000/TCP State: Running Started: Mon, 17 Feb 2020 09:50:44 +0800 Ready: True Restart Count: 1 Volume Mounts: <none> Environment Variables: <none> Conditions: Type Status Initialized True Ready True PodScheduled True No volumes. QoS Class: BestEffort Tolerations: <none> No events. [root@kube-master ~]# kubectl describe replicaset nginx-2187705812 Name: nginx-2187705812 #副本控制器的名稱 Namespace: default #所屬命名空間 Image(s): docker.io/nginx Selector: pod-template-hash=2187705812,run=nginx Labels: pod-template-hash=2187705812 run=nginx Replicas: 1 current / 1 desired Pods Status: 1 Running / 0 Waiting / 0 Succeeded / 0 Failed No volumes. No events. [root@kube-master ~]# kubectl describe deployment nginx Name: nginx #deployment的名稱 Namespace: default #所屬的命名空間 CreationTimestamp: Mon, 20 Jan 2020 13:14:29 +0800 Labels: run=nginx Selector: run=nginx Replicas: 1 updated | 1 total | 1 available | 0 unavailable StrategyType: RollingUpdate MinReadySeconds: 0 RollingUpdateStrategy: 1 max unavailable, 1 max surge Conditions: Type Status Reason ---- ------ ------ Available True MinimumReplicasAvailable OldReplicaSets: <none> NewReplicaSet: nginx-2187705812 (1/1 replicas created) #副本控制器 No events. [root@kube-master ~]# kubectl describe namespace default Name: default #命名空間名稱 Labels: <none> Status: Active No resource quota. No resource limits.
能夠看到默認pod的名稱是在replicaset名稱的基礎上建立,而replicaset名稱又是在deployment名稱基礎上建立。
2)kubectl delete刪除鏡像實例
理論上來講,pod做爲能夠被操做的最小單元,刪除鏡像實例時應該刪除pod。可是在實際操做過程當中,想要刪除鏡像實例應該對deployment(部署控制器)鏡像進行刪除。由於deployment(部署控制器)其中一個功能就是聲明副本數量和狀態,當deployment內的pod被刪除時,爲了確保副本數量和狀態不變,會自動生成行的副本。
演示以下:
#首先嚐試刪除pod [root@kube-master ~]# kubectl delete pod nginx-2187705812-qhrr1 pod "nginx-2187705812-qhrr1" deleted #當即查看pod,能夠看到pod名稱發生了變化,但仍是存在的 [root@kube-master ~]# kubectl get pods NAME READY STATUS RESTARTS AGE nginx-2187705812-llnn1 0/1 ContainerCreating 0 6s #稍等一下子,能夠看下node節點上的docker實例 #node2節點上的鏡像實例已經沒有了 [root@kube-node2 ~]# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES #在node1節點上生成了新的鏡像實例 [root@kube-node1 ~]# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 5dab3629cd31 docker.io/nginx "nginx -g 'daemon ..." 29 seconds ago Up 28 seconds k8s_nginx.92d20176_nginx-2187705812-llnn1_default_bca68cc3-3a6b-11ea-af25-000c29d2651b_7ea84e24 bd8804d961e3 registry.access.redhat.com/rhel7/pod-infrastructure:latest "/usr/bin/pod" 37 seconds ago Up 35 seconds k8s_POD.17af0ba2_nginx-2187705812-llnn1_default_bca68cc3-3a6b-11ea-af25-000c29d2651b_b885408b #而後刪除deployment [root@kube-master ~]# kubectl delete deployment nginx deployment "nginx" deleted [root@kube-master ~]# kubectl get deployment No resources found. [root@kube-master ~]# kubectl get pods No resources found. #稍等一下子到node節點上查看docker實例 #節點node1上的鏡像實例已經沒有了 [root@kube-node1 ~]# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES #節點node2上也沒有生成新的鏡像實例 [root@kube-node2 ~]# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
3)kubectl create加載YAML文件生成deployment或pod
使用kubectl run在設定一個複雜需求時,須要使用很是長的語句,容易出錯且沒法保存。因此在這種狀況下,通常會使用YAML或JSON文件。
製做deployment文件,用於建立或刪除mysql資源。
[root@kube-master ~]# vim mysql-deployment.yaml kind: Deployment apiVersion: extensions/v1beta1 metadata: #當前資源元數據(屬性)(Deployment) name: mysql #Deployment名稱 spec: #當前資源內容詳細定義(Deployment) replicas: 1 #Pod副本期待數量 template: #Pod模板 metadata: #當前資源元數據(屬性)(Pod) labels: #標籤 name: mysql spec: #當前資源內容詳細定義(Pod) containers: #Pod中容器列表定義 - name: mysql #docker容器實例名稱的一部分 image: docker.io/mysql/mysql-server #對應的Docker鏡像 imagePullPolicy: IfNotPresent #鏡像拉取策略,若是本地沒有則下載 ports: #容器對外開放端口號 - containerPort: 3306 #容器對外開放端口號 protocol: TCP #協議類型 env: #環境變量 - name: MYSQL_ROOR_PASSWORD #這裏設置的是mysql的root密碼 value: "hello123"
根據YAML文件建立Deployment資源
#在節點上下載鏡像或加載鏡像 [root@kube-node1 ~]# docker pull docker.io/mysql/mysql-server Using default tag: latest Trying to pull repository docker.io/mysql/mysql-server ... latest: Pulling from docker.io/mysql/mysql-server c7127dfa6d78: Pull complete 530b30ab10d9: Pull complete 59c6388c2493: Pull complete cca3f8362bb0: Pull complete Digest: sha256:7cd104d6ff11f7e6a16087f88b1ce538bcb0126c048a60cd28632e7cf3dbe1b7 Status: Downloaded newer image for docker.io/mysql/mysql-server:latest [root@kube-node2 ~]# docker pull docker.io/mysql/mysql-server Using default tag: latest Trying to pull repository docker.io/mysql/mysql-server ... latest: Pulling from docker.io/mysql/mysql-server c7127dfa6d78: Pull complete 530b30ab10d9: Pull complete 59c6388c2493: Pull complete cca3f8362bb0: Pull complete Digest: sha256:7cd104d6ff11f7e6a16087f88b1ce538bcb0126c048a60cd28632e7cf3dbe1b7 Status: Downloaded newer image for docker.io/mysql/mysql-server:latest #使用YAML文件建立Deployment [root@kube-master ~]# kubectl create -f mysql-deployment.yaml deployment "mysql" created [root@kube-master ~]# kubectl get deployment NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE mysql 1 1 1 1 19s nginx 1 1 1 1 29d [root@kube-master ~]# kubectl get replicaset NAME DESIRED CURRENT READY AGE mysql-2118902952 1 1 1 32s nginx-2187705812 1 1 1 29d [root@kube-master ~]# kubectl get pod NAME READY STATUS RESTARTS AGE mysql-2118902952-q93x0 1/1 Running 0 38s nginx-2187705812-cbb2s 1/1 Running 2 29d
根據YAML文件刪除Deployment資源
[root@kube-master ~]# kubectl delete -f mysql-deployment.yaml deployment "mysql" deleted [root@kube-master ~]# kubectl get deployment NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE nginx 1 1 1 1 29d [root@kube-master ~]# kubectl get replicaset NAME DESIRED CURRENT READY AGE nginx-2187705812 1 1 1 29d [root@kube-master ~]# kubectl get pod NAME READY STATUS RESTARTS AGE nginx-2187705812-cbb2s 1/1 Running 2 29d
舉例:當docker查看時的容器實例名稱爲k8s_mysql-1.694e284a_mysql-1683940614-fm6pf_default_57c24466-5222-11ea-90a6-000c29d2651b_ca0ad9f0,其中mysql-1是YAML中設置的容器實例的部分名稱,mysql-1683940614-fm6pf爲pod名稱,default爲所屬命名空間。
4)kubectl get獲取信息
kubectl get用的比較多,經常使用來獲取當前k8s的一些基本信息,能夠獲取內容以下
[root@kube-master ~]# kubectl get certificatesigningrequest persistentvolumeclaim cluster pod clusterrole poddisruptionbudget clusterrolebinding podsecuritypolicy componentstatus podtemplate configmap replicaset cronjob replicationcontroller daemonset resourcequota deployment role endpoints rolebinding event secret horizontalpodautoscaler securitycontextconstraints ingress service job serviceaccount limitrange statefulset namespace status networkpolicy storageclass node thirdpartyresource persistentvolume thirdpartyresourcedata
5)kubectl describe獲取詳細信息
kubectl describe能夠用於獲取一個或多個對象的詳細信息,若是沒有指定對象,將返回該類型的全部對象詳細信息。能夠操做類型以下:
[root@kube-master ~]# kubectl describe certificatesigningrequest persistentvolume configmap persistentvolumeclaim cronjob pod daemonset poddisruptionbudget deployment replicaset endpoints replicationcontroller horizontalpodautoscaler resourcequota ingress secret job securitycontextconstraints limitrange service namespace serviceaccount networkpolicy statefulset node storageclass
6)kubectl logs查看pod中鏡像日誌
kubectl logs是排除故障時的重要信息來源(端口號10250)
[root@kube-master ~]# kubectl logs mysql-1683940614-fm6pf [Entrypoint] MySQL Docker Image 8.0.19-1.1.15 [Entrypoint] No password option specified for new database. [Entrypoint] A random onetime password will be generated. [Entrypoint] Initializing database 2020-02-18T07:43:25.144854Z 0 [System] [MY-013169] [Server] /usr/sbin/mysqld (mysqld 8.0.19) initializing of server in progress as process 22 2020-02-18T07:43:29.167752Z 5 [Warning] [MY-010453] [Server] root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option. [Entrypoint] Database initialized 2020-02-18T07:43:33.495646Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.19) starting as process 70 2020-02-18T07:43:34.341561Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed. 2020-02-18T07:43:34.395848Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.19' socket: '/var/lib/mysql/mysql.sock' port: 0 MySQL Community Server - GPL. 2020-02-18T07:43:34.652186Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: '/var/run/mysqld/mysqlx.sock' Warning: Unable to load '/usr/share/zoneinfo/iso3166.tab' as time zone. Skipping it. Warning: Unable to load '/usr/share/zoneinfo/leapseconds' as time zone. Skipping it. Warning: Unable to load '/usr/share/zoneinfo/tzdata.zi' as time zone. Skipping it. Warning: Unable to load '/usr/share/zoneinfo/zone.tab' as time zone. Skipping it. Warning: Unable to load '/usr/share/zoneinfo/zone1970.tab' as time zone. Skipping it. [Entrypoint] GENERATED ROOT PASSWORD: m0Nam=OGyDYD3hQowgibazQeRim [Entrypoint] ignoring /docker-entrypoint-initdb.d/* 2020-02-18T07:43:39.876989Z 10 [System] [MY-013172] [Server] Received SHUTDOWN from user root. Shutting down mysqld (Version: 8.0.19). 2020-02-18T07:43:41.794714Z 0 [System] [MY-010910] [Server] /usr/sbin/mysqld: Shutdown complete (mysqld 8.0.19) MySQL Community Server - GPL. [Entrypoint] Server shut down [Entrypoint] Setting root user as expired. Password will need to be changed before database can be used. [Entrypoint] MySQL init process done. Ready for start up. [Entrypoint] Starting MySQL 8.0.19-1.1.15 2020-02-18T07:43:42.235423Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.19) starting as process 1 2020-02-18T07:43:42.988688Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed. 2020-02-18T07:43:43.047254Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.19' socket: '/var/lib/mysql/mysql.sock' port: 3306 MySQL Community Server - GPL. 2020-02-18T07:43:43.175377Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: '/var/run/mysqld/mysqlx.sock' bind-address: '::' port: 33060
7)kubectl exec容器內執行命令
有兩種使用方式,第一種方式直接跟隨pod容器和命令,以下:
[root@kube-master ~]# kubectl exec mysql-1683940614-fm6pf cat /etc/my.cnf # For advice on how to change settings please see # http://dev.mysql.com/doc/refman/8.0/en/server-configuration-defaults.html [mysqld] # # Remove leading # and set to the amount of RAM for the most important data # cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%. # innodb_buffer_pool_size = 128M # # Remove leading # to turn on a very important data integrity option: logging # changes to the binary log between backups. # log_bin # # Remove leading # to set options mainly useful for reporting servers. # The server defaults are faster for transactions and fast SELECTs. # Adjust sizes as needed, experiment to find the optimal values. # join_buffer_size = 128M # sort_buffer_size = 2M # read_rnd_buffer_size = 2M # Remove leading # to revert to previous value for default_authentication_plugin, # this will increase compatibility with older clients. For background, see: # https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_default_authentication_plugin # default-authentication-plugin=mysql_native_password skip-host-cache skip-name-resolve datadir=/var/lib/mysql socket=/var/lib/mysql/mysql.sock secure-file-priv=/var/lib/mysql-files user=mysql pid-file=/var/run/mysqld/mysqld.pid
第二種方式,使用-it選項進入到容器內部,再進行操做
[root@kube-master ~]# kubectl exec mysql-1683940614-fm6pf -it bash bash-4.2# ls bin etc lib64 proc sys boot healthcheck.cnf media root tmp dev healthcheck.sh mnt run usr docker-entrypoint-initdb.d home mysql-init-complete sbin var entrypoint.sh lib opt srv bash-4.2# exit exit
8)kubectl cp物理機與容器間拷貝
kubectl cp [Pod名稱]:[容器內的絕對目錄] [物理機的絕對目錄],這是將容器內文件拷貝到物理機上。
kubectl cp [物理機的絕對目錄] [Pod名稱]:[容器內的絕對目錄],這是將物理機上文件拷貝到容器內。
注意:在使用kubectl cp命令時,須要保證容器內存在tar工具
[root@kube-master ~]# kubectl exec mysql-1683940614-fm6pf -it bash bash-4.2# yum -y install tar ...... bash-4.2# exit exit #從物理機拷貝到容器中 [root@kube-master ~]# kubectl cp mysql-deployment.yaml mysql-1683940614-fm6pf:/ [root@kube-master ~]# kubectl exec mysql-1683940614-fm6pf -it bash bash-4.2# ls bin etc lib64 opt srv boot healthcheck.cnf media proc sys dev healthcheck.sh mnt root tmp docker-entrypoint-initdb.d home mysql-deployment.yaml run usr entrypoint.sh lib mysql-init-complete sbin var bash-4.2# ls /var/log/ mysqld.log tallylog yum.log bash-4.2# exit exit #從容器中拷貝到物理機上 [root@kube-master ~]# kubectl cp mysql-1683940614-fm6pf:/var/log/mysqld.log /root/ tar: Removing leading `/' from member names error: open /root: is a directory #須要指定文件名 [root@kube-master ~]# kubectl cp mysql-1683940614-fm6pf:/var/log/mysqld.log /root/mysqld.log tar: Removing leading `/' from member names [root@kube-master ~]# ls anaconda-ks.cfg example.yaml mysql-deployment.yaml mysqld.log
9)kubectl attach實時監測Pod容器
kubectl attach有些相似於tail -f [文件],實時查看文件的變化,固然這裏查看的是日誌文件。
[root@kube-master ~]# kubectl attach mysql-1683940614-fm6pf If you don't see a command prompt, try pressing enter. [Entrypoint] MySQL Docker Image 8.0.19-1.1.15 [Entrypoint] No password option specified for new database. [Entrypoint] A random onetime password will be generated. 2020-02-19T02:38:03.354513Z 0 [System] [MY-013169] [Server] /usr/sbin/mysqld (mysqld 8.0.19) initializing of server in progress as process 22 2020-02-19T02:38:09.595816Z 5 [Warning] [MY-010453] [Server] root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option. [Entrypoint] Initializing database 2020-02-19T02:38:15.425724Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.19) starting as process 70 2020-02-19T02:38:17.312841Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed. 2020-02-19T02:38:17.404453Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.19' socket: '/var/lib/mysql/mysql.sock' port: 0 MySQL Community Server - GPL. [Entrypoint] Database initialized 2020-02-19T02:38:17.505308Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: '/var/run/mysqld/mysqlx.sock' Warning: Unable to load '/usr/share/zoneinfo/iso3166.tab' as time zone. Skipping it. Warning: Unable to load '/usr/share/zoneinfo/leapseconds' as time zone. Skipping it. Warning: Unable to load '/usr/share/zoneinfo/tzdata.zi' as time zone. Skipping it. Warning: Unable to load '/usr/share/zoneinfo/zone.tab' as time zone. Skipping it. Warning: Unable to load '/usr/share/zoneinfo/zone1970.tab' as time zone. Skipping it. [Entrypoint] GENERATED ROOT PASSWORD: BUnMen@NIqjoSb@s^0cH@KD3GAK 2020-02-19T02:38:23.591510Z 10 [System] [MY-013172] [Server] Received SHUTDOWN from user root. Shutting down mysqld (Version: 8.0.19). [Entrypoint] ignoring /docker-entrypoint-initdb.d/* 2020-02-19T02:38:25.338584Z 0 [System] [MY-010910] [Server] /usr/sbin/mysqld: Shutdown complete (mysqld 8.0.19) MySQL Community Server - GPL. [Entrypoint] Server shut down [Entrypoint] Setting root user as expired. Password will need to be changed before database can be used. [Entrypoint] MySQL init process done. Ready for start up. [Entrypoint] Starting MySQL 8.0.19-1.1.15 2020-02-19T02:38:26.005956Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.19) starting as process 1 2020-02-19T02:38:26.917802Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed. 2020-02-19T02:38:26.978916Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.19' socket: '/var/lib/mysql/mysql.sock' port: 3306 MySQL Community Server - GPL. 2020-02-19T02:38:27.019494Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: '/var/run/mysqld/mysqlx.sock' bind-address: '::' port: 33060
10)kubectl管理集羣中deployment資源和service服務
涉及到如下命令:
kubectl edit 使用默認編輯器編輯服務器上定義的資源
kubectl replace 使用配置文件或標準輸入替換資源
kubectl patch 使用patch補丁修改、更新資源的字段
kubectl apply 使用配置文件或標準輸入更改資源
kubectl scale 擴容或縮容 Deployment、ReplicaSet、Replication Controller或 Job 中Pod數量。scale也能夠指定多個前提條件,如:當前副本數量或 --resource-version ,進行伸縮比例設置前,系統會先驗證前提條件是否成立。
kubectl autoscale 使用autoscaler自動設置在k8s集羣中運行的pod數量(水平自動伸縮)。指定Deployment、ReplicaSet或ReplicationController,並建立已經定義好資源的自動伸縮器。使用自動伸縮器能夠根據須要自動增長或減小系統中部署的pod數量。
kubectl cordon 將節點標記爲不可調度
kubectl uncordon 將節點標記爲能夠調度
kubectl drain 將節點標記爲維護狀態
清理一下存在的pod
[root@kube-master ~]# kubectl get pod NAME READY STATUS RESTARTS AGE mysql-1683940614-fm6pf 1/1 Running 1 23h nginx-2187705812-cbb2s 1/1 Running 3 30d [root@kube-master ~]# kubectl delete -f mysql-deployment.yaml deployment "mysql" deleted [root@kube-master ~]# kubectl delete deployment nginx deployment "nginx" deleted [root@kube-master ~]# kubectl get pod No resources found.
製做nginx-deployment.yaml資源文件和nginx-service.yaml服務配置文件
[root@kube-master ~]# vim nginx-deployment.yaml kind: Deployment apiVersion: extensions/v1beta1 metadata: name: nginx spec: replicas: 1 template: metadata: labels: name: nginx spec: containers: - name: nginx image: docker.io/nginx:latest imagePullPolicy: IfNotPresent ports: - containerPort: 80 protocol: TCP [root@kube-master ~]# vim nginx-service.yaml kind: Service apiVersion: v1 metadata: name: nginx spec: type: NodePort ports: #經過端口映射容許外部訪問 - protocol: TCP #協議 port: 8081 #集羣內部訪問端口 nodePort: 31001 #節點(物理機)上的端口 targetPort: 80 #(容器)目標端口 selector: name: nginx
經過這兩個文件建立deployment和service,並查看
[root@kube-master ~]# kubectl create -f nginx-deployment.yaml deployment "nginx" created [root@kube-master ~]# kubectl create -f nginx-service.yaml service "nginx" created [root@kube-master ~]# kubectl get deployment NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE nginx 1 1 1 1 14m [root@kube-master ~]# kubectl get pod NAME READY STATUS RESTARTS AGE nginx-1011335894-g18mm 1/1 Running 0 14m [root@kube-master ~]# kubectl get service NAME CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes 10.254.0.1 <none> 443/TCP 35d nginx 10.254.33.167 <nodes> 8081:31001/TCP 50s
注意:須要確保節點服務器開啓轉發功能
[root@kube-node1 ~]# vim /etc/sysctl.conf //這是永久開啓轉發功能 //添加或修改以下行 net.ipv4.ip_forward = 1 [root@kube-node1 ~]# sysctl -p //刷新使參數生效 net.ipv4.ip_forward = 1
接着就可使用外網訪問該服務了。
也測試一下Pod間訪問
[root@kube-master ~]# kubectl create -f mysql-deployment.yaml deployment "mysql" created [root@kube-master ~]# kubectl exec mysql-1683940614-p700p -it bash bash-4.2# curl 10.254.33.167:8081 #8081能夠訪問 <!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> bash-4.2# curl 10.254.33.167:80 #80不能夠訪問 curl: (7) Failed connect to 10.254.33.167:80; Connection timed out bash-4.2# exit exit
A.kubectl edit編輯器修改
[root@kube-master ~]# kubectl edit service nginx # Please edit the object below. Lines beginning with a '#' will be ignored, # and an empty file will abort the edit. If an error occurs while saving this f ile will be # reopened with the relevant failures. # apiVersion: v1 kind: Service metadata: creationTimestamp: 2020-02-20T03:08:14Z name: nginx namespace: default resourceVersion: "178017" selfLink: /api/v1/namespaces/default/services/nginx uid: 3bda3bd7-538e-11ea-b10c-000c29d2651b spec: clusterIP: 10.254.33.167 ports: - nodePort: 31002 #修改外網端口 port: 8081 protocol: TCP targetPort: 80 selector: name: nginx sessionAffinity: None type: NodePort status: loadBalancer: {} [root@kube-master ~]# kubectl get service NAME CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes 10.254.0.1 <none> 443/TCP 36d nginx 10.254.33.167 <nodes> 8081:31002/TCP 43m
外網查看
B.kubectl replace
[root@kube-master ~]# kubectl get service nginx -o yaml > nginx_replace.yaml [root@kube-master ~]# vim nginx_replace.yaml apiVersion: v1 kind: Service metadata: creationTimestamp: 2020-02-20T03:08:14Z name: nginx namespace: default resourceVersion: "181141" selfLink: /api/v1/namespaces/default/services/nginx uid: 3bda3bd7-538e-11ea-b10c-000c29d2651b spec: clusterIP: 10.254.33.167 ports: - nodePort: 31001 #注意,部分老版本是不能改回原來的IP地址的,不然會報錯 port: 8081 protocol: TCP targetPort: 80 selector: name: nginx sessionAffinity: None type: NodePort status: loadBalancer: {} [root@kube-master ~]# kubectl replace -f nginx_replace.yaml service "nginx" replaced [root@kube-master ~]# kubectl get service nginx NAME CLUSTER-IP EXTERNAL-IP PORT(S) AGE nginx 10.254.33.167 <nodes> 8081:31001/TCP 3h
外網查看
C.kubectl patch
#更換鏡像 [root@kube-master ~]# kubectl patch pod nginx-1011335894-g18mm -p '{"spec":{"containers":[{"name":"nginx","image":"docker.io/richarvey/nginx-php-fpm:latest"}]}}' "nginx-1011335894-g18mm" patched [root@kube-master ~]# kubectl describe pod nginx-1011335894-g18mm Name: nginx-1011335894-g18mm Namespace: default Node: kube-node1/192.168.128.111 Start Time: Wed, 19 Feb 2020 16:30:06 +0800 Labels: name=nginx pod-template-hash=1011335894 Status: Running IP: 10.255.30.2 Controllers: ReplicaSet/nginx-1011335894 Containers: nginx: Container ID: docker://4b75f63c4235535c3ee2209cff5e0733d2a0a933f0fec0154599a05d8a496b2f Image: docker.io/richarvey/nginx-php-fpm:latest Image ID: docker-pullable://docker.io/richarvey/nginx-php-fpm@sha256:a312a923fe36bfb630621480a03a799285936cb90a143fbb76e9da29815c05dc Port: 80/TCP State: Running Started: Thu, 20 Feb 2020 15:18:57 +0800 Last State: Terminated Reason: Completed Exit Code: 0 Started: Thu, 20 Feb 2020 09:02:18 +0800 Finished: Thu, 20 Feb 2020 15:16:22 +0800 Ready: True Restart Count: 2 Volume Mounts: <none> Environment Variables: <none> Conditions: Type Status Initialized True Ready True PodScheduled True No volumes. QoS Class: BestEffort Tolerations: <none> Events: FirstSeen LastSeen Count From SubObjectPath Type Reason Message --------- -------- ----- ---- ------------- -------- ------ ------- 6m 6m 1 {kubelet kube-node1} spec.containers{nginx} Normal Killing Killing container with docker id 60052f3ed6fc: pod "nginx-1011335894-g18mm_default(08986775-52f2-11ea-a0eb-000c29d2651b)" container "nginx" hash changed (549914156 vs 3468627213), it will be killed and re-created. 6m 6m 1 {kubelet kube-node1} spec.containers{nginx} Normal Pulling pulling image "docker.io/richarvey/nginx-php-fpm:latest" 6h 4m 3 {kubelet kube-node1} Warning MissingClusterDNS kubelet does not have ClusterDNS IP configured and cannot create Pod using "ClusterFirst" policy. Falling back to DNSDefault policy. 4m 4m 1 {kubelet kube-node1} spec.containers{nginx} Normal Pulled Successfully pulled image "docker.io/richarvey/nginx-php-fpm:latest" 4m 4m 1 {kubelet kube-node1} spec.containers{nginx} Normal Created Created container with docker id 4b75f63c4235; Security:[seccomp=unconfined] 4m 4m 1 {kubelet kube-node1} spec.containers{nginx} Normal Started Started container with docker id 4b75f63c4235 #能夠看到新的鏡像可使用php [root@kube-master ~]# kubectl exec nginx-1011335894-g18mm -it bash bash-5.0# php -v PHP 7.4.2 (cli) (built: Jan 24 2020 07:18:03) ( NTS ) Copyright (c) The PHP Group Zend Engine v3.4.0, Copyright (c) Zend Technologies with Zend OPcache v7.4.2, Copyright (c), by Zend Technologies
外網查看一下
D.kubectl apply
[root@kube-master ~]# vim nginx-service.yaml kind: Service apiVersion: v1 metadata: name: nginx spec: type: NodePort ports: - protocol: TCP port: 8081 nodePort: 31003 targetPort: 80 selector: name: nginx [root@kube-master ~]# kubectl apply -f nginx-service.yaml service "nginx" configured [root@kube-master ~]# kubectl get service NAME CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes 10.254.0.1 <none> 443/TCP 36d nginx 10.254.33.167 <nodes> 8081:31003/TCP 4h
外網查看
E.kubectl scale
scale橫向擴展是k8s這類編輯器平臺的重要功能之一。
[root@kube-master ~]# kubectl get pod -o wide | grep nginx NAME READY STATUS RESTARTS AGE IP NODE nginx-1011335894-g18mm 1/1 Running 2 23h 10.255.30.2 kube-node1 [root@kube-master ~]# kubectl scale --current-replicas=1 --replicas=3 deployment/nginx deployment "nginx" scaled [root@kube-master ~]# kubectl get deployment nginx NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE nginx 3 3 3 3 23h [root@kube-master ~]# kubectl get pod -o wide | grep nginx nginx-1011335894-g18mm 1/1 Running 2 23h 10.255.30.2 kube-node1 nginx-1011335894-sdjg7 1/1 Running 0 2m 10.255.87.3 kube-node2 nginx-1011335894-tktff 1/1 Running 0 2m 10.255.30.3 kube-node1
F.kubectl autoscale
autoscale經過設置最大值和最小值,自動根據負載進行調整。
[root@kube-master ~]# kubectl autoscale deployment nginx --min=2 --max=5 deployment "nginx" autoscaled
注意:最大值不能小於當前存在的數量
H.kubectl cordon或uncordon
當節點服務器發生故障時,須要對服務器進行封鎖。完成修復時,再進行解封。
[root@kube-master ~]# kubectl get node -o wide NAME STATUS AGE EXTERNAL-IP kube-node1 Ready 35d <none> kube-node2 Ready 35d <none> [root@kube-master ~]# kubectl get pod -o wide | grep nginx nginx-1011335894-g18mm 1/1 Running 2 23h 10.255.30.2 kube-node1 nginx-1011335894-sdjg7 1/1 Running 0 17m 10.255.87.3 kube-node2 nginx-1011335894-tktff 1/1 Running 0 17m 10.255.30.3 kube-node1 [root@kube-master ~]# kubectl cordon kube-node2 node "kube-node2" cordoned [root@kube-master ~]# kubectl get node -o wide NAME STATUS AGE EXTERNAL-IP kube-node1 Ready 35d <none> kube-node2 Ready,SchedulingDisabled 35d <none> [root@kube-master ~]# kubectl get pod -o wide | grep nginx #原有的並不會當即消失 nginx-1011335894-g18mm 1/1 Running 2 1d 10.255.30.2 kube-node1 nginx-1011335894-sdjg7 1/1 Running 0 41m 10.255.87.3 kube-node2 nginx-1011335894-tktff 1/1 Running 0 41m 10.255.30.3 kube-node1 [root@kube-master ~]# kubectl scale --replicas=4 deployment nginx deployment "nginx" scaled [root@kube-master ~]# kubectl get pod -o wide | grep nginx #但不會再往node2節點添加新的Pod nginx-1011335894-g18mm 1/1 Running 2 1d 10.255.30.2 kube-node1 nginx-1011335894-hb9rz 1/1 Running 0 11s 10.255.30.4 kube-node1 nginx-1011335894-sdjg7 1/1 Running 0 42m 10.255.87.3 kube-node2 nginx-1011335894-tktff 1/1 Running 0 42m 10.255.30.3 kube-node1
解封
[root@kube-master ~]# kubectl uncordon kube-node2 node "kube-node2" uncordoned [root@kube-master ~]# kubectl get node -o wide NAME STATUS AGE EXTERNAL-IP kube-node1 Ready 35d <none> kube-node2 Ready 35d <none>
I.kubectl drain
drain比cordon多了一個驅逐節點上的Pod,用的相對較多。解封同樣使用的是uncordon
[root@kube-master ~]# kubectl get node -o wide NAME STATUS AGE EXTERNAL-IP kube-node1 Ready 35d <none> kube-node2 Ready 35d <none> [root@kube-master ~]# kubectl get pod -o wide | grep nginx nginx-1011335894-g18mm 1/1 Running 2 1d 10.255.30.2 kube-node1 nginx-1011335894-hb9rz 1/1 Running 0 4m 10.255.30.4 kube-node1 nginx-1011335894-sdjg7 1/1 Running 0 47m 10.255.87.3 kube-node2 nginx-1011335894-tktff 1/1 Running 0 47m 10.255.30.3 kube-node1 [root@kube-master ~]# kubectl drain kube-node1 node "kube-node1" cordoned pod "nginx-1011335894-g18mm" evicted pod "nginx-1011335894-tktff" evicted pod "nginx-1011335894-hb9rz" evicted node "kube-node1" drained [root@kube-master ~]# kubectl get node -o wide NAME STATUS AGE EXTERNAL-IP kube-node1 Ready,SchedulingDisabled 35d <none> kube-node2 Ready 35d <none> [root@kube-master ~]# kubectl get pod -o wide | grep nginx nginx-1011335894-d0mxj 1/1 Running 0 29s 10.255.87.5 kube-node2 nginx-1011335894-hhz1f 1/1 Running 0 29s 10.255.87.4 kube-node2 nginx-1011335894-sdjg7 1/1 Running 0 48m 10.255.87.3 kube-node2 nginx-1011335894-zh2zw 1/1 Running 0 29s 10.255.87.6 kube-node2
解封
[root@kube-master ~]# kubectl uncordon kube-node1 node "kube-node1" uncordoned [root@kube-master ~]# kubectl get node -o wide NAME STATUS AGE EXTERNAL-IP kube-node1 Ready 35d <none> kube-node2 Ready 35d <none> [root@kube-master ~]# kubectl get pod -o wide | grep nginx nginx-1011335894-d0mxj 1/1 Running 0 1m 10.255.87.5 kube-node2 nginx-1011335894-hhz1f 1/1 Running 0 1m 10.255.87.4 kube-node2 nginx-1011335894-sdjg7 1/1 Running 0 49m 10.255.87.3 kube-node2 nginx-1011335894-zh2zw 1/1 Running 0 1m 10.255.87.6 kube-node2
(5).模板文件
衆所周知的槽點:k8s沒有提供對apiVersion的任何指導,目前能夠先對照https://matthewpalmer.net/kubernetes-app-developer/articles/kubernetes-apiversion-definition-guide.html這個網址來選擇,後期我會單獨寫一篇。
Pod模板文件大體以下:
apiVersion: v1 #必選,指定api版本, kind: Pod #必選,指定建立角色的資源類型 metadata: #必選,指定資源的元數據(屬性) name: [String] #必選,資源的名稱,在同一個命名空間內必須惟一 namespace: [String] #可選,資源所處的命名空間,默認default labels: #可選,自定義標籤列表 - [name]: [String] #數組總體複數可選,自定義標籤內容 annotations: #可選,自定義註釋列表 - [name]: [String] #數組總體複數可選,自定義註釋內容 spec: #必選,指定資源內容的詳細定義 containers: #必選,指定Pod中容器列表 - name: [String] #指定容器名稱(docker容器實例名稱的一部分) images: [String] #必選,指定容器鏡像 imagesPullPolicy: [Always | Never | IfNotPresent] #可選,指定鏡像拉取策略,Always表示老是下載鏡像,Never表示只使用本地鏡像,IfNotPresent表示若是本地沒有鏡像再下載。默認IfNotPresent command: [String] #可選,指定容器的啓動命令,若是沒有指定使用打包時使用的啓動命令 args: [String] #可選,指定容器啓動時的命令參數 workingDir: [String] #可選,指定容器的工做目錄,沒有指定使用Docker的默認 ports: #可選,指定容器對外開放端口列表 - name: [String] #數組總體複數可選,端口名稱 containerPort: [int] #容器對外開放端口 hostPort: [number] #映射到主機端口號,通常設置爲與containerPort相同 protocol: [String] #端口協議 env: #可選,指定容器運行的環境變量列表 - name: [String] #數組總體複數可選,環境變量名稱 value: [String] #環境變量的值 resources: #可選,指定容器運行的資源限制 limits: #容器運行資源上限 cpu: [String] #CPU資源,1(核)=1000m,m表示千分之一個內核,故有兩種書寫方式 memory: [String] #內存資源,單位Mi/Gi/M/G...。在k8s中單位沒有i,表示以1000做爲進制單位;單位有i,表示1024做爲進制單位 requests: #容器運行資源下限 cpu: [String] memory: [String] volumeMounts: #可選,指定掛載到容器內部的存儲卷配置 - name: [String] #數組總體複數可選,引用Pod中定義的共享存儲卷(volume)的名稱 mountPath: [String] #存儲卷掛載到容器內部的絕對地址,應少於512字符 readOnly: [String] #存儲卷是否爲只讀模式 livenessProbe: #指定對Pod內容器進行健康檢查的設置。當探測無響應幾回時,將會自動重啓該容器,exec、httpGet和tcpSocket三選一進行設置 exec: #三選一設置,執行檢測 command: [String] #設置執行命令或腳本 httpGet: #三選一設置,http獲取檢測 path: [String] #URI地址 port: [number] #端口號 host: [String] #主機地址 scheme: [String] #跳轉協議 HttpHeaders: #http頭信息 - name: [String] #信息名稱 value: [String] #對應的值 tcpSocket: #三選一設置,tcp套字節檢測 port: [number] #端口號 initialDelaySeconds: [number] #容器啓動後首次探測時間,單位秒 timeoutSeconds: [number] #檢測超時時間,單位秒 periodSeconds: [number] #檢測間隔時間,單位秒 successThreshold: [number] #成功閾值,檢測成功多少次算健康 failureThreshold: [number] #失敗閾值,檢測失敗多少次須要重啓 securityContext: #安全環境 privileged: [Boolean] #是否容許特權,通常都是不容許false restartPolicy: [Always | Never |OnFailure] #可選,Pod重啓策略,Always表示只要Pod中止就重啓,Never表示Pod中止後不重啓,OnFailure表示正常退出不重啓。默認Always nodeSelector: [object] #可選,節點選擇器 imagePullSecrets: #可選,鏡像拉取密鑰。k8s能夠建立secret(機密)註冊表,其內主要保存docker鏈接的服務器、用戶名和密碼等信息。 - name: [String] #數組總體複數可選,經過secret(機密)註冊表名稱,選擇鏈接不一樣的docker倉庫 hostNetwork: [Boolean] #是否使用主機網絡,默認爲false volumes: #可選,在該Pod上定義共享存儲卷列表 - name: [String] #數組總體複數可選,存儲卷名稱。類型多選一,並不止如下四種 emptyDir: {} #類型爲emptyDir的存儲卷,與Pod同生命週期的臨時目錄,保證容器意外死亡時數據存留,爲空值。 hostPath: #類型爲hostPath的存儲卷,將主機文件系統上的文件或目錄掛載到Pod中 path: [String] #主機文件系統上的文件或目錄,與容器中vloumeMounts設置裏的mountPath相呼應 secret: #類型爲secret(機密)的存儲卷,將主機文件系統上的文件或目錄掛載到Pod中 scretname: [String] #secret名稱 items: #項目 - key: [String] #關鍵詞 path: [String] #擴展地址,相對路徑。容器中實際路徑爲vloumeMounts設置裏的mountPath+擴展地址 configMap: #類型爲configMap的存儲卷 name: [String] #configMap名稱 items: #項目 - key: [String] #關鍵詞 path: [String] #擴展地址,相對路徑。容器中實際路徑爲vloumeMounts設置裏的mountPath+擴展地址
固然,有些容器能夠設置的屬性:name、image、command、args、workingDir、ports、env、resources、volumeMounts、livenessProbe、readinessProbe、livecycle、terminationMessagePath、imagePullPolicy、securityContext、stdin、stdinOnce、tty。
service配置文件模板以下:
apiVersion: v1 #必選,指定api版本 kind: Service #必選,指定建立角色的資源類型 matadata: #必選,指定資源的元數據(屬性) name: [String] #必選,資源名稱,在同一命名空間內必選惟一 namespace: [String] #可選,資源所處的命名空間,默認default labels: #可選,自定義標籤列表 - [name]: [String] #數組總體複數可選,自定義標籤內容 annotations: #可選,自定義註釋列表 - [name]: [String] #數組總體複數可選,自定義註釋內容 spec: #必選,指定資源內容的詳細定義 selector: #必選,選擇具備指定標籤的Pod做爲管理範圍 - [name]: [String] #管理範圍定義 type: [ClusterIP | NodePort | LoadBalancer] #可選,指定服務的訪問方式,默認爲ClusterIP。 #ClusterIP表示集羣IP(虛擬IP)模式,用於k8s集羣內部Pod的互相訪問,在節點上kube-proxy經過設置iptables規則進行轉發; #NodePort表示節點端口模式,用於外部訪問k8s集羣內部的Pod,在外部客戶端上經過節點的IP和端口訪問服務; #LoadBalancer表示負載均衡器模式,使用外接的負載均衡完成服務的負載分發,須要在spec.status.loadBalancer指定外部負載均衡器的IP地址,並同時定義ClusterIP和NodePort用於公有云。 clusterIP: [String] #指定當前服務在集羣內部的IP地址。服務訪問方式爲ClusterIP時可選,若是不指定系統自動分配;服務訪問方式爲LoadBalancer時,必須手動設置。 sessionAffinity: [ClientIP | None] #可選,是否支持Session,默認爲空(None)。Session表示同一個源IP地址的客戶端請求都發給同一個後端Pod ports: #可選,服務對外開放端口列表 - name: [String] #數組總體複數可選,端口自定義名稱 protocol: [TCP | UDP] #端口協議,默認TCP port: [int] #提供給內部Pod訪問使用的端口 targetPort: [int] #Pod內部服務的端口 nodePort: [int] #提供給外部訪問的節點上的端口 status: loadBalancer: ingress: ip: [String] #外接負載均衡器的IP地址 hostname: [String] #外接負載均衡器的主機名
注意:使用端口映射時須要保證節點上的iptables開啓轉發功能(iptables -P FORWARD ACCEPT(臨時轉發))
參考:https://kubernetes.io/zh/docs/reference/kubectl/overview/
https://www.runoob.com/w3cnote/yaml-intro.html
https://blog.csdn.net/luanpeng825485697/article/details/83753260
https://blog.csdn.net/phantom_111/article/details/79427144
https://blog.csdn.net/u011230692/article/details/84490874
https://blog.csdn.net/watermelonbig/article/details/79693962