K8S 中 kubectl 详解

Posted 爱show的小卤蛋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了K8S 中 kubectl 详解相关的知识,希望对你有一定的参考价值。

一、资源管理办法

1.1 陈述式资源管理方法

  • kubernetes集群管理集群资源的唯一入口是通过相应的方法调用apiserver的接口
  • kubectl 是官方的CLI命令行工具,用于与apiserver 进行通信,将用户在命令行输入的命令,组织并转化为apiserver能识别的信息,进而实现管理k8s各种资源的一种有 效途径
  • kubectl 的命令大全
kubectl --help
k8s中文文档: https://docs.kubernetes.org.cn/683.html
  • 对资源的增、删、查操作比较方便,但对改的操作就不容易了

查看版本信息

kubectl version

查看资源对象简写

kubectl api-resources

[root@master01 opt]# 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
events                            ev           events.k8s.io                  true         Event
daemonsets                        ds           extensions                     true         DaemonSet
deployments                       deploy       extensions                     true         Deployment
ingresses                         ing          extensions                     true         Ingress
networkpolicies                   netpol       extensions                     true         NetworkPolicy
podsecuritypolicies               psp          extensions                     false        PodSecurityPolicy
replicasets                       rs           extensions                     true         ReplicaSet
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

查看集群信息

kubectl cluster-info

配置kubectl自动补全

source <(kubectl completion bash)

node节点查看日志

journactl -u kubectl -f

1.2 声明式资源管理办法

通过yaml资源配置清单文件在实现资源的管理

kubectl create/apply -f *.yaml

二、基本信息查看

kubectl get <resource> [-o wide|json|yaml] [-n namespace]
获取资源的相关信息,-n指定命令空间,-o指定输出格式
resource可以是具体资源名称,如pod nginx- xxx;也可以是资源类型,如pod; 或者all (仅展示几种核心资源,并不完整)
--all-namespaces 或-A :表示显示所有命令空间,
--show-labels :显示所有标签
-l app:仅显示标签为app的资源
-l app=nginx:仅显示包含app标签,且值为nginx的资源
-o:指定输出格式

查看master 节点状态

kubectl get componentstatuses 
kubectl get cs

查看命名空间

kubectl get namespace
kubectl get ns
命令空间的作用:用于允许不同命令空间的相同类型的资源重名的

描述某个资源的详细信息(deployment,pod等)

kubectl describe deployment nginx-wl -n kube-public
kubectl describe pod  pod名 -n kube-public

查看default命名空间的所有资源

kubectl get all [-n default]

查看命名空间kube-public 中的pod信息

kubectl get pods -n  kube-public

kubectl exec 跨主机登录容器,docker exec 只能在在容器所在主机上登录

kubectl exec  -it 容器名 bash -n kube-public

删除(重启)pod资源

由于存在deployment/rc之类的副本控制器,删除pod也会重新拉起来

kubectl delete pod nginx-test-65c98cd596-mhzrz -n kube-public
若pod无法删除, 总是处于terminate状态, 则要强行删除pod
kubectl delete pod nginx-test-65c98cd596-qx6hg -n kube-public --force --grace-period=0
#grace-period表示过渡存活期,默认30s,在删除pod之前允许POD慢慢终止其上的容器进程,从而优雅退出,0表示立即终止pod

扩缩容

kubectl scale deployment -n kube-public nginx-test --replicas=3				#扩容
kubectl scale deployment -n kube-public nginx-test --replicas=1 			#缩容

删除副本控制器

kubectl delete deployment -n kube-public nginx-test
kubectl delete deployment/nginx-test01 -n kube-public

三、项目生命周期

项目的生命周期:创建------------->发布----------------------->更新--------------->回滚---------------->删除

3.1 创建 (kubectl run 命令)

  • 创建并运行一个或多个容器镜像
  • 创建一个deployment或job来管理容器
  • kubectl run --help
#启动 nginx实例,暴露容器端口 80 设置副本数 3
kubectl run nginx-demo --image=nginx:1.14 --port=80 --replicas=3

kubectl get pods
kubectl get all

kubectl get pod -w
#跟踪

注意:

3.2 发布(kubectl expose命令)

  • 将资源暴露为新的Service
  • kubectl expose --help

为deployment的nginx创建service,并通过service的80端口转发至容器的80端口上,service的名称为nginx-service,类型为NodePort,如不指定的话,就是Clusterip
kubectl expose deployment nginx-demo --port=80 --target-port=80 --name=nginx-service --type=NodePort

------------------------------------------------------------------------------------------------------------
Kubernetes之所以需要Service,一方面是因为Pod的IP不是固定的(Pod可能会重建),另一方面则是因为一组 Pod实例之间总会有负载均衡的需求。
Service通过Label Selector 实现的对一组的Pod的访问。
对于容器应用而言,Kubernetes 提供了基于VIP (虚拟IP)的网桥的 方式访问Service, 再由Service 重定向到相应的Pod。


用port映射target-port

service的类型:

  • ClusterIP: 提供一个集群内部的虚拟IP以供Pod访问( service默认类型)
  • NodePort:在每个Node.上打开一个端口以供外部访问,Kubernetes将会在每个Node上打开一个端口并且每个Node的端口都是一样的,通过NodeIp:NodePort的方式Kubernetes集群外部的程序可以访问Service。
    :每个端口只能是一种服务, 端口范围只能是30000-32767.
  • LoadBalancer:通过外部的负载均衡器来访问,通常在云平台部署LoadBalancer还需要额外的费用。
#查看pod网络状态详细信息和Service 暴露的端口
[root@master01 opt]# kubectl get pods,svc -o wide
NAME                              READY   STATUS    RESTARTS   AGE    IP           NODE     NOMINATED NODE   READINESS GATES
pod/nginx-demo-6594ff9fd8-889bk   1/1     Running   0          116m   10.244.1.4   node01   <none>           <none>
pod/nginx-demo-6594ff9fd8-9t9rt   1/1     Running   0          116m   10.244.2.3   node02   <none>           <none>
pod/nginx-demo-6594ff9fd8-qcmjp   1/1     Running   0          116m   10.244.2.4   node02   <none>           <none>

NAME                    TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE     SELECTOR
service/kubernetes      ClusterIP   10.96.0.1       <none>        443/TCP        3h37m   <none>
service/nginx           NodePort    10.110.47.18    <none>        80:30558/TCP   3h30m   app=nginx
service/nginx-service   NodePort    10.110.10.193   <none>        80:30948/TCP   103m    run=nginx-demo
#查看关联后端的节点
[root@master01 opt]# kubectl get endpoints 
NAME            ENDPOINTS                                   AGE
kubernetes      192.168.100.10:6443                         3h39m
nginx           <none>                                      3h31m
nginx-service   10.244.1.4:80,10.244.2.3:80,10.244.2.4:80   104m

测试负载均衡:

通过ipvsadm查看

node01上面操作,查看负载均衡端口

以上说明可以通过nodeIP加端口转发,也可以通过clusterip进行转发

3.3 更新(kubectl set 命令)

  • 更改现有应用资源一些信息
  • kubectl set --help
## 获取修改模板
kubectl set image --help
Examples:
  # Set a deployment's nginx container image to 'nginx:1.9.1', and its busybox container image to 'busybox'.
  kubectl set image deployment/nginx busybox=busybox nginx=nginx:1.9.1


## 查看当前nginx的版本号
curl -I http://192.168.80.30:31268

kubectl set image deployment.apps/nginx nginx-demo=nginx:1.15
kubectl get pods

## 更新完后再次查看nginx的版本号
curl -I http://192.168.80.30:31268

查看更新命令的帮助

获取修改模板

kubectl set image --help
Update existing container image(s) of resources.

 Possible resources include (case insensitive):

  pod (po), replicationcontroller (rc), deployment (deploy), daemonset (ds), replicaset (rs)

Examples:
  # Set a deployment's nginx container image to 'nginx:1.9.1', and its busybox container image to 'busybox'.
  kubectl set image deployment/nginx busybox=busybox nginx=nginx:1.9.1
  
  # Update all deployments' and rc's nginx container's image to 'nginx:1.9.1'
  kubectl set image deployments,rc nginx=nginx:1.9.1 --all
  
  # Update image of all containers of daemonset abc to 'nginx:1.9.1'
  kubectl set image daemonset abc *=nginx:1.9.1
  
  # Print result (in yaml format) of updating nginx container image from local file, without hitting the server
  kubectl set image -f path/to/file.yaml nginx=nginx:1.9.1 --local -o yaml

Options:
      --all=false: Select all resources, including uninitialized ones, in the namespace of the specified resource types
      --allow-missing-template-keys=true: If true, ignore any errors in templates when a field or map key is missing in
the template. Only applies to golang and jsonpath output formats.
      --dry-run=false: If true, only print the object that would be sent, without sending it.
  -f, --filename=[]: Filename, directory, or URL to files identifying the resource to get from a server.
  -k, --kustomize='': Process the kustomization directory. This flag can't be used together with -f or -R.
      --local=false: If true, set image will NOT contact api-server but run locally.
  -o, --output='': Output format. One of:
json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-file.
      --record=false: Record current kubectl command in the resource annotation. If set to false, do not record the
command. If set to true, record the command. If not set, default to updating the existing annotation value only if one
already exists.
  -R, --recursive=false: Process the directory used in -f, --filename recursively. Useful when you want to manage
related manifests organized within the same directory.
  -l, --selector='': Selector (label query) to filter on, not including uninitialized ones, supports '=', '==', and
'!='.(e.g. -l key1=value1,key2=value2)
      --template='': Template string or path to template file to use when -o=go-template, -o=go-template-file. The
template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].

Usage:
  kubectl set image (-f FILENAME | TYPE NAME) CONTAINER_NAME_1=CONTAINER_IMAGE_1 ... CONTAINER_NAME_N=CONTAINER_IMAGE_N
[options]

Use "kubectl options" for a list of global command-line options (applies to all commands).

查看当前ngnix版本号

curl -I http://192.168.100.20:30948
curl -I http://192.168.100.10:30948
curl -I http://192.168.100.30:30948#通过请求头看版本号

将版本更新到1.15版本

kubectl set image deployment.apps/nginx-demo nginx-demo=nginx:1.15

3.4 回滚(kubectl rollout)

  • 对资源进行回滚管理
  • kubectl rollout --help
## 查看历史版本
kubectl rollout history deployment/nginx-demo

## 执行回滚到上一个版本
kubectl rollout undo deployment/nginx-demo

## 执行回滚到指定版本
kubectl rollout undo deployment/nginx-demo --to-revision=1

## 检查回滚状态
kubectl rollout status deployment/nginx-demo

3.5 删除 kubectl delete

## 删除副本控制器
kubectl delete deployment/nginx-demo

## 删除service
kubectl delete service/nginx-svc

kubectl get all

以上是关于K8S 中 kubectl 详解的主要内容,如果未能解决你的问题,请参考以下文章

K8S 中 kubectl 详解

K8S 中 kubectl 详解

K8S 中 kubectl 详解

K8S 中 kubectl 详解

K8S 中 kubectl 详解

k8s学习-kubectl命令常用选项详解与实战