Kubernetes初学乍练(资源管理)

1、资源管理介绍

在Kubernetes中,所有的内容都抽象为资源,用户需要通过操作资源来管理Kubernetes。怎么理解,就好比我们常说的面向对象语言,一切皆对象。

  • Kubernetes的本质就是一个集群系统,用户可以在集群中部署各种服务,所谓的部署服务,其实就是在Kubernetes集群中运行一个个容器,并将指定的程序跑在容器中。
  • Kubernetes的最小管理单元你是Pod而不是容器,所以只能将容器放在Pod中,而Kubernetes一般也不会直接管理Pod,而是通过Pod控制器来管理Pod。
  • Pod提供服务之后,就需要考虑如何访问Pod中的服务,Kubernetes提供了Service资源实现这个功能。
  • 如果Pod中程序的数据需要持久化,Kubernetes还提供了各种存储系统。

2、资源管理方式

Kubernetes的资源管理方式分为三种:命令式对象管理,命令式对象配置,声明式对象配置。

2.1、命令式对象管理

kubectl是Kubernetes集群的命令行工具,通过它能够对集群本身进行管理,并能够在集群上进行容器化应用的安装和部署。

kubectl [command] [type] [name] [flags]
  • command:指定要对资源执行的操作,比如:create、get、delete
  • type:指定资源的类型,比如deployment、pod、service
  • name: 指定资源名称,名称大小写敏感
  • flags:指定额外的可选参数
# 查看所有的pod
kubectl get pods

NAME                     READY   STATUS    RESTARTS   AGE
nginx-55f8fd7cfc-gn5vc   1/1     Running   0          42m

# 查看某个pod
kubectl get pod pod名称

# 查看某个pod的运行详情
get pod pod名称 -o wide

# 查看某个pod,以yaml格式展示结果
kubectl get pod pod名称 -o yaml

Kubernetes允许对资源进行多种操作,可以通过 -- help查看详细的操作命令:

kubectl --help

kubectl controls the Kubernetes cluster manager.
# kubectl控制Kubernetes集群管理器

 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        Take a replication controller, service, deployment or pod and expose it as a new Kubernetes Service
  #暴露		  以复制控制器、服务、部署Pod为例,将其公开为新的Kubernetes服务
  run           Run a particular image on the cluster
  #运行         在集群中运行特定的镜像
  set           Set specific features on objects
  #设置         在对象上设置特定的功能
 
Basic Commands (Intermediate):
# 基本命令(过渡)
  explain       Documentation of resources
  #说明		  文档的参考资料
  get           Display one or many resources
  #获取		  显示一个或多个资源
  edit          Edit a resource on the server
  #编辑          在服务上编辑资源
  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     Auto-scale a Deployment, ReplicaSet, or ReplicationController
  #自动缩放

Cluster Management Commands:
# 集群管理命令
  certificate   Modify certificate resources.
  #整数
  cluster-info  Display cluster info
  #集群信息
  top           Display Resource (CPU/Memory/Storage) usage.
  cordon        Mark node as unschedulable
  # 警戒线      将节点标记为不可调度
  uncordon      Mark node as schedulable
  #             将节点标记为可调度
  drain         Drain node in preparation for maintenance
  taint         Update the taints on one or more nodes
  #污染		  更新一个或多个节点的污染

Troubleshooting and Debugging Commands:
# 故障处理和Debug命令
  describe      Show details of a specific resource or group of resources
  #描述         显示特定资源或资源组的详细信息
  logs          Print the logs for a container in a pod
  #日志		  打印一个容器的日志
  attach        Attach to a running container
  #附加         连接到正在运行的容器
  exec          Execute a command in a container
  #			   在容器中执行命令  
  port-forward  Forward one or more local ports to a pod
  #端口转发	     将一个或多个本地端口转发到一个pod
  proxy         Run a proxy to the Kubernetes API server
  #代理          运行Kubernetes API服务器的代理
  cp            Copy files and directories to and from containers.
  #拷贝		  从容器中复制文件和目录
  auth          Inspect authorization
  #             检查授权

Advanced Commands:
# 进阶命令
  diff          Diff live version against would-be applied version
  apply         Apply a configuration to a resource by filename or stdin
  #应用	      通过文件名或标准输入将配置应用到资源
  patch         Update field(s) of a resource using strategic merge patch
  #补丁		  使用策略合并补丁更新资源的字段
  replace       Replace a resource by filename or stdin
  #替换	      用文件名或标准输入替换资源
  wait          Experimental: Wait for a specific condition on one or many resources.
  #等待		  实验性:在一个或多个资源上等待特定的条件。
  convert       Convert config files between different API versions
  #转换		  在不同的API版本之间转换配置文件
  kustomize     Build a kustomization target from a directory or a remote url.
  #             从目录或远程url构建kustomization目标。
  
Settings Commands:
# 设置命令
  label         Update the labels on a resource
  #标签         更新资源上的标签
  annotate      Update the annotations on a resource
  #注释         更新资源上的注释
  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资源       打印服务器上支持的API资源
  api-versions  Print the supported API versions on the server, in the form of "group/version"
  config        Modify kubeconfig files
  #配置		  修改kubeconfig文件
  plugin        Provides utilities for interacting with plugins.
  #插件          提供与插件交互的实用程序
  version       Print the client and server version information
  #版本        打印客户端和服务器的版本信息
Usage:
  kubectl [flags] [options]

Kubernetes中所有的内容都抽象为资源,我们可以通过命令查看具体有哪些资源。

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 配置

应用实例

# 创建一个namespace
kubectl create namespace dev

# 获取namespace
kubect get namespace

NAME              STATUS   AGE
default           Active   2m3s
dev               Active   41s    # 我们上面刚创建的
kube-node-lease   Active   2m5s
kube-public       Active   2m5s
kube-system       Active   2m5s

# 在dev namesapce下创建并运行一个Nginx
 kubectl run nginx --image=nginx:1.17.1 -n dev
 说明:-n 指定namespace,如果不知名,则会创建在默认的default
 
# 查看dev的namespace下所有的pod
kubectl get pods -n dev

NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          54s

# 删除指定namespace下的指定Pod
kubectl delete pod nginx -n dev

# 删除指定的命名空间
kubectl delete namespace dev
  
kubectl get ns   # 发现已经没有dev了
NAME              STATUS   AGE
default           Active   8m41s
kube-node-lease   Active   8m43s
kube-public       Active   8m43s
kube-system       Active   8m43s

2.2、命令式对象配置

命令式对象配置就是使用命令配合配置文件一起来操作Kubernetes资源。

  1. 创建一个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
  1. 执行create命令,创建资源
kubectl create -f nginxpod.yaml
  1. 查看资源
kubectl get ns  # 查看命名空间
kubectl get pods -n dev  # 查看pods

kubectl get -f nginxpod.yaml  # 通过配置文件进行获取

NAME            STATUS   AGE
namespace/dev   Active   3m21s

NAME           READY   STATUS    RESTARTS   AGE
pod/nginxpod   1/1     Running   0          3m21s

4)删除资源

kubectl delete -f nginxpod.yaml

namespace "dev" deleted
pod "nginxpod" deleted

2.3、声明式对象配置

声明式对象配置是通过apply命令和配置文件去操作Kubernetes的资源,声明式对象配置和命令式对象配置类似,只不过声明式对象配置只有一个apply命令,apply相当于createpatch

kubectl apply -f nginxpod.yaml 
# 第一次执行
namespace/dev created
pod/nginxpod created

kubectl apply -f nginxpod.yaml 
# 第二次执行
namespace/dev unchanged
pod/nginxpod unchanged

声明式对象配置就是使用apply描述一个资源的最终状态(在yaml中定义状态)

使用apply操作资源:

​ 1)如果资源不存在,创建,相当于kubectl create

​ 2)如果资源存在,更新,相当于kubectl pathc

扩展

  • kubectl可以在node节点上运行吗

​ Kubectl的运行时需要进行配置的,它的配置文件是$HOME/.kube,如果想要在node节点上运行此命令,需要将master上的.kube文件复制到node节点上,即在master节点上执行下面命令:

scp -r  ~/.kube/ node1:~
  • 三种方式应该如何使用?

​ 创建/更新资源:使用声明式对象配置 kubectl apply -f xxx.yaml

​ 删除资源:使用命令式对象配置kubectl delete -f xxx.yaml

​ 查询资源:使用命令式对象管理kubectl get(describe)资源名称

原文地址:https://www.cnblogs.com/huiyichanmian/p/15094373.html