前言:
一个k8s集群搭建完毕后,仅仅是万里长征的第一步,不管是以什么方式搭建的集群,比如,kubeadm或者二进制安装的,也不管是多master集群还是单master集群,不管是生产环境还是测试环境,集群搭建的目的都是为了使用这个集群。(集群搭建是比较基础的问题,在此不予讨论了)
k8s集群不同于其他的容器管理平台,比如,openstack,openstack可以有更多的管理选择比如api,但k8s使用最多也最频繁的是命令行工具kubectl。因此,kubectl能否正确使用,能否熟练使用将会影响到你对集群管理的效率。
正文:
一,kubectl命令alias为 k
通常为了简化命令,我们可以使用alias命令将kubectl简化为k,本文后续将全部使用k代替kubectl。alias也非常简单。
[root@master ~]# whereis kubectl kubectl: /usr/bin/kubectl echo "alias k=/usr/bin/kubectl">>/etc/profile source /etc/profile
先查询出kubectl所在位置,然后将alias写入环境变量配置里,激活环境变量即可。
二,kubectl的帮助
[root@master ~]# k --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 Take a replication controller, service, deployment or pod and expose it as a new Kubernetes Service 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: 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 proxy Run a proxy to the Kubernetes API server 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 kustomize Build a kustomization target from a directory or a remote url. 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-versions Print the supported API versions on the server, in the form of "group/version" config Modify kubeconfig files plugin Provides utilities for interacting with plugins. version Print the client and server version information 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).
很多同学看到某个命令茫茫多的参数,估计就菊花一紧,其实,不用慌,大部分都是不经常使用的,常用的也就那么几个参数。不过,从另一个方面来说,参数多,说明这个命令功能强大嘛,能干的事情非常多,也说明了k8s的复杂性。
这里要说一下,该命令帮助贴心的说明了有哪些部分,比如,
Basic Commands (Beginner)----------基础命令,最基础的命令, 这些命令应该全部掌握 Basic Commands (Intermediate)------------基础命令,中度使用命令,这些命令也应该全部掌握 Deploy Commands----------部署命令,这些命令需要掌握,autoscale除外 Cluster Management Commands---------集群管理命令,cluster-info,top,taint需要熟练掌握。 Troubleshooting and Debugging Commands---------debug和总结报告类型的命令 describe,logs,exec,port-forward,proxy需要熟练掌握 Advanced Commands------------高级进阶命令,apply,patch,replace,需要熟练掌握 Settings Commands----------------基本设置命令,label,annotate,completion需要熟练掌握 Other Commands--------------------其它类型的命令,api-resources,api-version,config,version,plugin需要熟练掌握
三,k8s常用参数
Basic Commands (Beginner): create Create a resource from a file or from stdin.
这个是非常常用的参数,比如下面这个命令,将会快速的部署一个NGINX到集群内:
k create deployment nginx --image nginx:1.19
此时查看pod,会发现是这样的:
kube-system kube-scheduler-c7n.cnn 1/1 Running 0 122m [root@master ~]# k get pods -A NAMESPACE NAME READY STATUS RESTARTS AGE database mysql2-5db57c8bc8-7bwbg 1/1 Running 3 3d18h default nfs-client-provisioner-6fc484bd4f-pjxm7 1/1 Running 2 2d23h default nginx-7b54d48599-x2zc5 0/1 ContainerCreating 0 33s
containercreating表示正在拉取镜像,生成pod ,等待镜像拉取完成后,将端口暴露出来:
[root@master ~]# k expose deployment nginx --port 80 --type NodePort service/nginx exposed
此时,将会有一个service建立,并且在集群外的机器上可以访问到这个pod了,30067就是刚才建立的pod暴露的端口号:
[root@master ~]# k get svc -A NAMESPACE NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE database mysql2 NodePort 10.106.38.0 <none> 3306:32222/TCP 3d18h default kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 27d default nginx NodePort 10.96.201.101 <none> 80:30067/TCP 73s
此时,打开浏览器输入任意一个集群内所在机器的ip+端口号30067就可以访问到nginx的首页啦。
资源清单
k api-resources
[root@master ~]# k 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
这个命令是在Other Commands里面的,直接 kubectl api-resources,这个非常重要,k8s的管理其实也主要是围绕着各种各样的资源来管理的。
第一列是所有k8s里的资源名称,常见的比如namespace,pods,nodes,StorageClass,service,statefulsets,deployments等等。
第二列是资源的缩写,比如,services=svc,pods=po,StorageClass=sc,PersistentVolumeClaim=pvc,PersistentVolume=pv等等。因此,比如查询所有namespaces有哪些,命令可以简化成这样:
[root@master ~]# k get ns NAME STATUS AGE database Active 3d23h default Active 27d kube-node-lease Active 27d kube-public Active 27d kube-system Active 27d
查询所有的pods,命令可以简化成这样:
[root@master ~]# k get po -A NAMESPACE NAME READY STATUS RESTARTS AGE database mysql2-5db57c8bc8-7bwbg 1/1 Running 4 3d23h default nfs-client-provisioner-6fc484bd4f-pjxm7 1/1 Running 3 3d4h default nginx-7b54d48599-x2zc5 1/1 Running 1 4h41m default test-pod 0/1 Pending 0 3d4h kube-system coredns-6c76c8bb89-tfcrm 1/1 Running 5 27d kube-system coredns-6c76c8bb89-vnlwg 1/1 Running 5 27d kube-system etcd-c7n.cnn 1/1 Running 6 27d kube-system kube-apiserver-c7n.cnn 1/1 Running 5 3d21h kube-system kube-controller-manager-c7n.cnn 1/1 Running 2 6h49m kube-system kube-flannel-ds-djwmq 1/1 Running 4 4d kube-system kube-flannel-ds-f5gtd 1/1 Running 5 4d kube-system kube-flannel-ds-k5jpf 1/1 Running 4 4d kube-system kube-proxy-7v5mj 1/1 Running 5 27d kube-system kube-proxy-mtttm 1/1 Running 5 27d kube-system kube-proxy-zwmwf 1/1 Running 6 27d kube-system kube-scheduler-c7n.cnn 1/1 Running 1 6h44m
第三例是资源的apigroup,比如编写jobs相关的资源清单文件,apiversion就必须是batch这个apigroup啦,当然,/ 后面还需要通过 k api-versions 这个命令查询。
比如这个定时任务资源清单文件:
apiVersion: batch/v1beta1 kind: CronJob metadata: name: hello spec: schedule: "*/1 * * * *" jobTemplate: spec: template: spec: containers: - name: hello image: busybox args: - /bin/sh - -c - date; echo Hello world!!!!!!! restartPolicy: OnFailure
第四列是资源是否必须和namespace关联,比如,nodes就不能通过namespace隔离,但pods可以通过namespace隔离,假如有两个不同的namespace A和Bnamespace,k8s会认为 A中运行的nginx-1.20.1和B中运行的nginx-1.20.1是两个不同的pod,并且在定义或者使用这些资源的时候,如果该列为true值,那么,必须要指定namespace,否则使用default这个namespace,如果该列为false值,那么,在定义资源的时候不需要指定namespace。
第五列是资源定义的时候kind的值,比如,要定义一个jobs资源,kind的值必须是Job(注意,这里是区分大小写的哦,切记!!!!!!),上面示例的第二行cronjob对应的kind的值就必须是CronJob 。