十年河东,十年河西,莫欺少年穷
学无止境,精益求精
1、K8s资源管理介绍
- 在Kubernetes中,所有的内容都抽象为资源,用户需要通过操作资源来管理Kubernetes。
 - Kubernetes的本质就是一个集群系统,用户可以在集群中部署各种服务。所谓的部署服务,其实就是在Kubernetes集群中运行一个个的容器,并将指定的程序跑在容器中。
 - Kubernetes的最小管理单元是Pod而不是容器,所以只能将容器放在
 
Pod
- 中,而Kubernetes一般也不会直接管理Pod,而是通过
 
Pod控制器
- 来管理Pod的。
 - Pod提供服务之后,就需要考虑如何访问Pod中的服务,Kubernetes提供了
 
Service
- 资源实现这个功能。
 - 当然,如果Pod中程序的数据需要持久化,Kubernetes还提供了各种
 
存储
- 系统。
 
学习kubernets的核心,就是学习如何对集群中的Pod、Pod控制器、Service、存储等各种资源进行操作。
2、YAML语法介绍
- YAML是一个类似于XML、JSON的标记性语言。它强调的是以“数据”为中心,并不是以标记语言为重点。因而YAML本身的定义比较简单,号称是“一种人性化的数据格式语言”。
 - YAML的语法比较简单,主要有下面的几个:
 
- 大小写敏感。
 - 使用缩进表示层级关系。
 - 缩进不允许使用tab,只允许空格(低版本限制)。
 - 缩进的空格数不重要,只要相同层级的元素左对齐即可。
 - ‘#’表示注释。
 
- YAML支持以下几种数据类型:
 
- 常量:单个的、不能再分的值。
 - 对象:键值对的集合,又称为映射/哈希/字典。
 - 数组:一组按次序排列的值,又称为序列/列表。
 
我们可以使用Yaml转Json工具来完成Yaml文件的编写工作,参考网址:http://www.json2yaml.com/
2.1、Yaml常量
#常量,就是指的是一个简单的值,字符串、布尔值、整数、浮点数、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 # 字符串过多的情况可以折成多行,每一行都会转换成一个空格注意,在yaml语法中,冒号后面必须要带上空格,否则会报错。
2.2、Yaml对象
# 对象
# 形式一(推荐):
xudaxian:    
    name: 许大仙
    age: 16
# 形式二(了解):
xuxian: { name: 许仙, age: 18 }2.3、Yaml数组
# 数组
# 形式一(推荐):
address:
    - 江苏
    - 北京
# 形式二(了解):
address: [江苏,上海]3、K8s资源管理方式
k8s资源管理方式分为三种,分别为:命令式对象管理、命令式对象配置、声明式对象配置
3.1、命令式对象管理:直接使用命令去操作kubernetes的资源。
- kubectl是kubernetes集群的命令行工具,通过它能够对集群本身进行管理,并能够在集群上进行容器化应用的安装和部署。
 - kubectl命令的语法如下:
 
kubectl [command] [type] [name] [flags]- command:指定要对资源执行的操作,比如create、get、delete。可通过 kubectl --help 查看所有的 command 指令
 - type:指定资源的类型,比如deployment、pod、service。 可通过kubectl api-resources 查看所有的 type 值
 - name:指定资源的名称,名称大小写敏感。
 - flags:指定额外的可选参数。
 
示例:
kubectl get pods --查看所有的pod
kubectl get pod pod_name  --查看某个Pod
kubectl get pod pod_name -o yaml  --以yaml的形式展示某个Pod信息
kubectl get pod pod_name -o json  --以json的形式展示某个pod信息通过 kubectl --help 查看所有 command 指令


[root@master ~]# kubectl --help
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).View Code
基本命令:
命令  | 翻译  | 命令作用  | 
create  | 创建  | 创建一个资源  | 
edit  | 编辑  | 编辑一个资源  | 
get  | 获取  | 获取一个资源  | 
patch  | 更新  | 更新一个资源  | 
delete  | 删除  | 删除一个资源  | 
explain  | 解释  | 展示资源文档  | 
运行与调试命令:
命令  | 翻译  | 命令作用  | 
run  | 运行  | 在集群中运行一个指定的镜像  | 
expose  | 暴露  | 暴露资源为Service  | 
describe  | 描述  | 显示资源内部信息  | 
logs  | 日志  | 输出容器在Pod中的日志  | 
attach  | 缠绕  | 进入运行中的容器  | 
exec  | 执行  | 执行容器中的一个命令  | 
cp  | 复制  | 在Pod内外复制文件  | 
rollout  | 首次展示  | 管理资源的发布  | 
scale  | 规模  | 扩(缩)容Pod的数量  | 
autoscale  | 自动调整  | 自动调整Pod的数量  | 
高级命令:
命令  | 翻译  | 命令作用  | 
apply  | 应用  | 通过文件对资源进行配置  | 
label  | 标签  | 更新资源上的标签  | 
其他命令:
命令  | 翻译  | 命令作用  | 
apply  | 应用  | 通过文件对资源进行配置  | 
label  | 标签  | 更新资源上的标签  | 
通过 kubectl api-resources 查看所有 type 值


[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        VolumeAttachmentView Code
集群级别资源
资源名称  | 缩写  | 资源作用  | 
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  |    | 配置  | 
应用示例
kubectl create namespace dev --创建一个命名空间
kubectl get ns  --获取命名空间 这里使用简写
kubectl run nginx --image=nginx:1.17.1 -n dev --在dev命名空间 运行一个nginx pod
kubectl get pods -n dev --查看名为dev的namespace下的所有Pod,如果不加-n,默认就是default的namespace
kubectl delete pod nginx -n dev --删除dev下的pod,
kubectl delete namespace dev  --删除命名空间 dev3、命令式对象配置
- 命令式对象配置:通过命令和配置文件去操作kubernetes的资源。
 
创建一个nginxpod.yaml,内容如下:
apiVersion: v1
kind: Namespace
metadata:
  name: dev
---
apiVersion: v1
kind: Pod
metadata:
  name: nginxpod
  namespace: dev
spec:
  containers:
    - name: nginx-containers
      image: nginx:1.17.1注: --- 三个小横杠代表又一个对象的开始
kubectl create -f nginxpod.yaml
执行get命令,查看资源:
kubectl get -f nginxpod.yaml执行delete 命令,删除资源
kubectl delete -f nginxpod.yaml- 命令式对象配置的方式操作资源,可以简单的认为:命令+yaml配置文件(里面是命令需要的各种参数)。
 
4、声明式对象配置
- 声明式对象配置:通过apply命令和配置文件去操作kubernetes的资源。
 - 声明式对象配置和命令式对象配置类似,只不过它只有一个apply命令。
 - apply相当于create和patch。即,不存在便创建,存在便更新
 
如上述的yaml文件,使用声明式配置语法如下:
kubectl apply -f nginxpod.yaml- 声明式对象配置就是使用apply描述一个资源的最终状态(在yaml中定义状态)。
 - 使用apply操作资源:
 
- 如果资源不存在,就创建,相当于kubectl create。
 - 如果资源存在,就更新,相当于kubectl patch。
 
- 总结
 - 创建和更新资源使用声明式对象配置:kubectl apply -f xxx.yaml。
 - 删除资源使用命令式对象配置:kubectl delete -f xxx.yaml。
 - 查询资源使用命令式对象管理:kubectl get(describe) 资源名称。
 
5、如何快速的编写yaml文件
5.1 使用kubectl create命令生成yaml文件
- 此种方式适用于没有真正部署资源。
 - 使用kubectl create命令生成yaml文件:
 
kubectl create deployment nginx --image=nginx:1.17.1 --dry-run=client -n dev -o yaml yaml内容会输出到屏幕上。
  如果yaml文件太长,可以写入到指定的文件中 
kubectl create deployment nginx --image=nginx:1.17.1 --dry-run=client -n dev -o yaml > test.yaml
参考:https://www.yuque.com/fairy-era/yg511q/gqx2mr
@天才卧龙的博客
    
    
    










