kubernetes的资源管理 1 资源管理介绍 在Kubernetes中,所有的内容都抽象为资源,用户需要通过操作资源来管理Kubernetes。
Kubernetes的本质就是一个集群系统,用户可以在集群中部署各种服务。所谓的部署服务,其实就是在Kubernetes集群中运行一个个的容器,并将指定的程序跑在容器中。 Kubernetes的最小管理单元是Pod而不是容器,所以只能将容器放在Pod中,而Kubernetes一般也不会直接管理Pod,而是通过Pod控制器来管理Pod的。 Pod提供服务之后,就需要考虑如何访问Pod中的服务,Kubernetes提供了Service资源实现这个功能。 当然,如果Pod中程序的数据需要持久化,Kubernetes还提供了各种存储系统。
学习kubernets的核心,就是学习如何对集群中的Pod、Pod控制器、Service、存储等各种资源进行操作。
2 YAML语法介绍 2.1 YAML语法介绍 YAML是一个类似于XML、JSON的标记性语言。它强调的是以“数据”为中心,并不是以标记语言为重点。因而YAML本身的定义比较简单,号称是“一种人性化的数据格式语言”。
YAML的语法比较简单,主要有下面的几个:
○大小写敏感。
○使用缩进表示层级关系。
○缩进不允许使用tab,只允许空格(低版本限制)。
○缩进的空格数不重要,只要相同层级的元素左对齐即可。
○‘#’表示注释。
YAML支持以下几种数据类型:
○常量:单个的、不能再分的值。
○对象:键值对的集合,又称为映射/哈希/字典。
○数组:一组按次序排列的值,又称为序列/列表。
2.2 YAML语法示例 2.2.1 YAML常量 1 2 3 4 5 6 7 8 9 10 11 12 #常量,就是指的是一个简单的值,字符串、布尔值、整数、浮点数、NUll、时间、日期 # 布尔类型 c1: true # 整型 c2: 123456 # 浮点类型 c3: 3.14 # null类型 c4: ~ # 使用~表示null # 日期类型 c5: 2019-11-11 # 日期类型必须使用ISO 8601格式,即yyyy-MM-dd # 时间类型 c6: 2019-11-11T15:02:31+08.00 # 时间类型使用ISO 8601格式,时间和日期之间使用T连接,最后使用+代表时区 # 字符串类型 c7: haha # 简单写法,直接写值,如果字符串中间有特殊符号,必须使用双引号或单引号包裹 c8: line1 line2 # 字符串过多的情况可以折成多行,每一行都会转换成一个空格
2.2.2 对象 1 2 3 4 5 6 7 \# 对象 # 形式一(推荐): xudaxian: name: wjy age: 20 # 形式二(了解): xuxian: { name: wjy, age: 20 }
2.2.3 数组 1 2 3 4 5 6 7 \# 数组 # 形式一(推荐): address: - 江苏 - 北京 # 形式二(了解): address: [江苏,上海]
3 资源管理方式 3.1 资源管理方式 命令式对象管理:直接使用命令去操作kubernetes的资源。
1 [root@master ~]# kubectl run nginx3 --image=192.168.20.119/library/nginx:latest
命令式对象配置:通过命令配置和配置文件去操作kubernetes的资源。
1 [root@master ~]# kubectl create/patch -f nginx-pod.yaml
声明式对象配置:通过apply命令和配置文件去操作kubernetes的资源。
1 [root@master ~]# kubectl apply -f nginx-pod.yaml
类型
操作
适用场景
优点
缺点
命令式对象管理
对象
测试
简单
只能操作活动对象,无法审计、跟踪
命令式对象配置
文件
开发
可以审计、跟踪
项目大的时候,配置文件多,操作麻烦
声明式对象配置
目录
开发
支持目录操作
意外情况下难以调试
3.2 命令式对象管理 3.2.1 kubectl命令 ●kubectl是kubernetes集群的命令行工具,通过它能够对集群本身进行管理,并能够在集群上进行容器化应用的安装和部署。 ●kubectl命令的语法如下:
1 kubectl [command] [type] [name] [flags]
●command:指定要对资源执行的操作,比如create、get、delete。 ●type:指定资源的类型,比如deployment、pod、service。 ●name:指定资源的名称,名称大小写敏感。 ●flags:指定额外的可选参数。
示例:查看所有的pod
1 2 3 4 5 6 [root@master ~]# kubectl get pods NAME READY STATUS RESTARTS AGE nginx 1/1 Running 0 15h nginx-674ff86d-6cjt9 0/1 ImagePullBackOff 0 15h nginx1-cc97d58b4-st5mx 1/1 Running 0 38h nginx3 1/1 Running 0 5m15s
示例:查看某个pod
1 2 3 [root@master ~]# kubectl get pods nginx #加上pod名称 NAME READY STATUS RESTARTS AGE nginx 1/1 Running 0 15h
示例:查看某个pod,以yaml格式展示结果
1 [root@master ~]# kubectl get pods nginx -o yaml
3.2.2 操作(command )kubernetes允许对资源进行多种操作,可以通过–help查看详细的操作命令:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 [root@master ~]# kubectl -h kubectl controls the Kubernetes cluster manager. Find more information at: https://kubernetes.io/docs/reference/kubectl/overview/ Basic Commands (Beginner): create Create a resource from a file or from stdin. expose 使用 replication controller, service, deployment 或者 pod 并暴露它作为一个 新的 Kubernetes Service run 在集群中运行一个指定的镜像 set 为 objects 设置一个指定的特征 Basic Commands (Intermediate): explain 查看资源的文档 get 显示一个或更多 resources edit 在服务器上编辑一个资源 delete Delete resources by filenames, stdin, resources and names, or by resources and label selector Deploy Commands: rollout Manage the rollout of a resource scale Set a new size for a Deployment, ReplicaSet or Replication Controller autoscale 自动调整一个 Deployment, ReplicaSet, 或者 ReplicationController 的副本数量 Cluster Management Commands: certificate 修改 certificate 资源. cluster-info 显示集群信息 top Display Resource (CPU/Memory/Storage) usage. cordon 标记 node 为 unschedulable uncordon 标记 node 为 schedulable drain Drain node in preparation for maintenance taint 更新一个或者多个 node 上的 taints Troubleshooting and Debugging Commands: describe 显示一个指定 resource 或者 group 的 resources 详情 logs 输出容器在 pod 中的日志 attach Attach 到一个运行中的 container exec 在一个 container 中执行一个命令 port-forward Forward one or more local ports to a pod proxy 运行一个 proxy 到 Kubernetes API server cp 复制 files 和 directories 到 containers 和从容器中复制 files 和 directories. auth Inspect authorization Advanced Commands: diff Diff live version against would-be applied version apply 通过文件名或标准输入流(stdin)对资源进行配置 patch 使用 strategic merge patch 更新一个资源的 field(s) replace 通过 filename 或者 stdin替换一个资源 wait Experimental: Wait for a specific condition on one or many resources. convert 在不同的 API versions 转换配置文件 kustomize Build a kustomization target from a directory or a remote url. Settings Commands: label 更新在这个资源上的 labels annotate 更新一个资源的注解 completion Output shell completion code for the specified shell (bash or zsh) Other Commands: alpha Commands for features in alpha api-resources Print the supported API resources on the server api-versions Print the supported API versions on the server, in the form of "group/version" config 修改 kubeconfig 文件 plugin Provides utilities for interacting with plugins. version 输出 client 和 server 的版本信息 Usage: kubectl [flags] [options] Use "kubectl <command> --help" for more information about a given command. Use "kubectl options" for a list of global command-line options (applies to all commands).
经常使用的操作如下所示:
① 基本命令:
命令
翻译
命令作用
create
创建
创建一个资源
edit
编辑
编辑一个资源
get
获取
获取一个资源
patch
更新
更新一个资源
delete
删除
删除一个资源
explain
解释
展示资源文档
② 运行和调试:
命令
翻译
命令作用
run
运行
在集群中运行一个指定的镜像
expose
暴露
暴露资源为Service
describe
描述
显示资源内部信息
logs
日志
输出容器在Pod中的日志
attach
缠绕
进入运行中的容器
exec
执行
执行容器中的一个命令
cp
复制
在Pod内外复制文件
rollout
首次展示
管理资源的发布
scale
规模
扩(缩)容Pod的数量
autoscale
自动调整
自动调整Pod的数量
③ 高级命令:
命令
翻译
命令作用
apply
应用
通过文件对资源进行配置
label
标签
更新资源上的标签
④ 其他命令:
命令
翻译
命令作用
cluster-info
集群信息
显示集群信息
version
版本
显示当前Client和Server的版本
3.2.3 资源类型(type) kubernetes中所有的内容都抽象为资源,可以通过下面的命令进行查看:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 [root@master ~]# kubectl api-resources NAME SHORTNAMES APIGROUP NAMESPACED KIND bindings true Binding componentstatuses cs false ComponentStatus configmaps cm true ConfigMap endpoints ep true Endpoints events ev true Event limitranges limits true LimitRange namespaces ns false Namespace nodes no false Node persistentvolumeclaims pvc true PersistentVolumeClaim persistentvolumes pv false PersistentVolume pods po true Pod podtemplates true PodTemplate replicationcontrollers rc true ReplicationController resourcequotas quota true ResourceQuota secrets true Secret serviceaccounts sa true ServiceAccount services svc true Service mutatingwebhookconfigurations admissionregistration.k8s.io false MutatingWebhookConfiguration validatingwebhookconfigurations admissionregistration.k8s.io false ValidatingWebhookConfiguration customresourcedefinitions crd,crds apiextensions.k8s.io false CustomResourceDefinition apiservices apiregistration.k8s.io false APIService controllerrevisions apps true ControllerRevision daemonsets ds apps true DaemonSet deployments deploy apps true Deployment replicasets rs apps true ReplicaSet statefulsets sts apps true StatefulSet tokenreviews authentication.k8s.io false TokenReview localsubjectaccessreviews authorization.k8s.io true LocalSubjectAccessReview selfsubjectaccessreviews authorization.k8s.io false SelfSubjectAccessReview selfsubjectrulesreviews authorization.k8s.io false SelfSubjectRulesReview subjectaccessreviews authorization.k8s.io false SubjectAccessReview horizontalpodautoscalers hpa autoscaling true HorizontalPodAutoscaler cronjobs cj batch true CronJob jobs batch true Job certificatesigningrequests csr certificates.k8s.io false CertificateSigningRequest leases coordination.k8s.io true Lease endpointslices discovery.k8s.io true EndpointSlice events ev events.k8s.io true Event ingresses ing extensions true Ingress ingressclasses networking.k8s.io false IngressClass ingresses ing networking.k8s.io true Ingress networkpolicies netpol networking.k8s.io true NetworkPolicy runtimeclasses node.k8s.io false RuntimeClass poddisruptionbudgets pdb policy true PodDisruptionBudget podsecuritypolicies psp policy false PodSecurityPolicy clusterrolebindings rbac.authorization.k8s.io false ClusterRoleBinding clusterroles rbac.authorization.k8s.io false ClusterRole rolebindings rbac.authorization.k8s.io true RoleBinding roles rbac.authorization.k8s.io true Role priorityclasses pc scheduling.k8s.io false PriorityClass csidrivers storage.k8s.io false CSIDriver csinodes storage.k8s.io false CSINode storageclasses sc storage.k8s.io false StorageClass volumeattachments storage.k8s.io false VolumeAttachment
经常使用的资源如下所示:
① 集群级别资源:
资源名称
缩写
资源作用
nodes
no
集群组成部分
namespaces
ns
隔离Pod
② Pod资源:
资源名称
缩写
资源作用
Pods
po
装载容器
③ Pod资源控制器:
资源名称
缩写
资源作用
replicationcontrollers
rc
控制Pod资源
replicasets
rs
控制Pod资源
deployments
deploy
控制Pod资源
daemonsets
ds
控制Pod资源
jobs
控制Pod资源
cronjobs
cj
控制Pod资源
horizontalpodautoscalers
hpa
控制Pod资源
statefulsets
sts
控制Pod资源
④ 服务发现资源:
资源名称
缩写
资源作用
services
svc
统一Pod对外接口
ingress
ing
统一Pod对外接口
⑤ 存储资源:
资源名称
缩写
资源作用
volumeattachments
存储
persistentvolumes
pv
存储
persistentvolumeclaims
pvc
存储
⑥ 配置资源:
资源名称
缩写
资源作用
configmaps
cm
配置
secrets
配置
3.2.4 应用示例 示例:创建一个namespace
1 2 [root@master ~]# kubectl create ns test #ns为namespace简写 namespace/test created
示例:获取namespace
1 2 3 4 5 6 7 8 9 [root@master ~]# kubectl get ns NAME STATUS AGE default Active 39h dev Active 15h kube-node-lease Active 39h kube-public Active 39h kube-system Active 39h kubernetes-dashboard Active 39h test Active 27s
示例:在刚才创建的namespace下创建并运行一个Nginx的Pod
1 2 [root@master ~]# kubectl run nginx --image=192.168.20.119/library/nginx:latest -n test pod/nginx created
示例:查看名为dev的namespace下的所有Pod,如果不加-n,默认就是default的namespace
1 2 3 [root@master ~]# kubectl get pods -n test NAME READY STATUS RESTARTS AGE nginx 1/1 Running 0 34s
示例:删除指定namespace下的指定Pod
1 2 [root@master ~]# kubectl delete pod nginx -n test pod "nginx" deleted
示例:删除指定的namespace
1 2 [root@master ~]# kubectl delete namespace test namespace "test" deleted
3.3 命令式对象配置 3.3.1 概述 命令式对象配置:通过命令配置和配置文件去操作kubernetes的资源。
3.3.2 应用示例 示例: 创建一个nginxpod.yaml,内容如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [root@master ~]# cat nginxpod.yaml apiVersion: v1 kind: Namespace metadata: name: test --- apiVersion: v1 kind: Pod metadata: name: nginxpod namespace: dev spec: containers: - name: nginx-containers image: 192.168.20.119/library/nginx:latest
执行create命令,创建资源
1 2 3 [root@master ~]# kubectl create -f nginxpod.yaml namespace/test created pod/nginxpod created
执行get命令,查看资源:
1 2 3 4 5 6 [root@master ~]# kubectl get -f nginxpod.yaml NAME STATUS AGE namespace/test Active 48s NAME READY STATUS RESTARTS AGE pod/nginxpod 1/1 Running 0 48s
执行delete命令,删除资源:
1 2 3 [root@master ~]# kubectl delete -f nginxpod.yaml namespace "test" deleted pod "nginxpod" deleted
3.3.3 总结 命令式对象配置的方式操作资源,可以简单的认为:命令+yaml配置文件(里面是命令需要的各种参数)。
3.4 声明式对象配置 3.4.1 概述 声明式对象配置:通过apply命令和配置文件去操作kubernetes的资源。 声明式对象配置和命令式对象配置类似,只不过它只有一个apply命令。 apply相当于create和patch。
3.4.2 应用示例 示例:
1 2 3 [root@master ~]# kubectl apply -f nginxpod.yaml namespace/test created pod/nginxpod created
3.4.3 总结 声明式对象配置就是使用apply描述一个资源的最终状态(在yaml中定义状态)。 使用apply操作资源: 如果资源不存在,就创建,相当于kubectl create。 如果资源存在,就更新,相当于kubectl patch。
3.5 使用方式推荐 ●创建和更新资源使用声明式对象配置:kubectl apply -f xxx.yaml。 ●删除资源使用命令式对象配置:kubectl delete -f xxx.yaml。 ●查询资源使用命令式对象管理:kubectl get(describe) 资源名称。
3.6 扩展:kubectl可以在Node上运行 kubectl的运行需要进行配置,它的配置文件是$HOME/.kube,如果想要在Node节点上运行此命令,需要将Master节点的.kube文件夹复制到Node节点上,即在Master节点上执行下面的操作:
1 [root@master ~]# scp -r /root/.kube/ root@node1:/root/
4 如何快速的编写yaml文件 此种方式适用于没有真正部署资源。 使用kubectl create命令生成yaml文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 [root@master ~]# kubectl create deployment nginx --image=192.168.20.119/library/nginx:latest --dry-run=client -n dev -o yaml > test.yaml [root@master ~]# cat test.yaml apiVersion: apps/v1 kind: Deployment metadata: creationTimestamp: null labels: app: nginx name: nginx namespace: dev spec: replicas: 1 selector: matchLabels: app: nginx strategy: {} template: metadata: creationTimestamp: null labels: app: nginx spec: containers: - image: 192.168.20.119/library/nginx:latest name: nginx resources: {} status: {}