k8s之kubectl常用命令

一. Kubectl常用命令

node相关

kubectl get nodes -o wide

kubectl describe node node01

 

容器命令

kubectl get pods -A -o wide

kubectl describe pod edgedns-xxx -n openname

kubectl exec -it pod_name /bin/sh

kubectl exec mypod -c pod -it -- /bin/sh

kubectl logs mypod -f -n openname

KUBE_EDITOR="vim" kubectl edit pod af -n ngc

 

网络

kubectl get subnets

三. kubectl命令行工具

3.1 kubectl

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

kubectl [command] [TYPE] [NAME] [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).

command:指定要对资源执行的操作,如create、get、describe和delete等。

Basic Commands (Beginner):
  create         Create a resource from a file or from stdin.
  expose    使用replication controller, service, deployment或者pod并暴露它作为一个新的k8s Service
  run            在集群中运行一个指定的镜像
  set            为 objects 设置一个指定的特征
 
Basic Commands (Intermediate):
  explain        查看资源的文档
  get            显示一个或更多 resources
  edit           在服务器上编辑一个资源
  delete    根据filenames, stdin, resources and names, or by resources and label selector删除资源
 
Deploy Commands:
  rollout        Manage the rollout of a resource
  scale          为 Deployment, ReplicaSet, Replication Controller 或者 Job 设置一个新的副本数量
  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 耗尽node
  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:
  apply          通过配置文件或标准输入流(stdin)对资源进行配置
  patch          使用 strategic merge patch 更新一个资源的 field(s)
  replace        通过 filename 或者 stdin替换一个资源
  wait           Experimental: Wait for one condition on one or many resources
  convert        在不同的 API versions 转换配置文件
 
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         Runs a command-line plugin
  version        输出 client 和 server 的版本信息 

TYPE:指定资源类型,资源类型是大小写敏感的,开发者能够以单数、复数和缩略的形式。例如: 

kubectl get pod pod1
kubectl get pods pod1
kubectl get po pod1 

NAME:指定资源的名称,名称大小写敏感。若省略名称,则会显示所有资源,例如:

kubectl get pods

flags:指定可选的参数。例如,可以使用-s或者--server参数指定kubernetes API server的地址和端口。

3.2 kubectl常用命令

kubectl作为kubernetes的命令行工具,主要的职责就是对集群中的资源的对象进行操作,这些操作包括对资源对象的创建、删除和查看等。下表中显示了kubectl支持的所有操作,以及这些操作的语法和描述信息:

kubectl编辑配置

kubectl edit (RESOURCE/NAME | -f FILENAME) [options]
$kubectl get deployment -o wide
NAME         READY   UP-TO-DATE   AVAILABLE   AGE     CONTAINERS   IMAGES   SELECTOR
nginx-test   2/3     3            2           4d18h   nginx-test   nginx    app=nginx
$kubectl edit deployment nginx-test
deployment.extensions/nginx-test edited
$ kubectl get deployment -o wide
NAME         READY   UP-TO-DATE   AVAILABLE   AGE     CONTAINERS   IMAGES   SELECTOR
nginx-test   2/2     2            2           4d18h   nginx-test   nginx    app=nginx

kubectl输出选项

kubectl默认的输出格式为纯文本格式,可以通过-o或者–output字段指定命令的输出格式。

kubectl [command] [TYPE] [NAME] -o=<output format>
kubectl get pod nginx-test-xxxxxxxxx -o yaml

3.3 k8s支持的资源

$ 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
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
addons                                         k3s.cattle.io                  true         Addon
helmcharts                                     k3s.cattle.io                  true         HelmChart
listenerconfigs                                k3s.cattle.io                  true         ListenerConfig
networkpolicies                   netpol       networking.k8s.io              true         NetworkPolicy
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
storageclasses                    sc           storage.k8s.io                 false        StorageClass
volumeattachments                              storage.k8s.io                 false        VolumeAttachment

3.4 kubeconfig

kubectl默认会从$HOME/.kube目录下查找文件名为config的文件,也能通过设置环境变量KUBECONFIG或者通过设置去指定其它 kubeconfig 文件。kubeconfig就是为访问集群所作的配置。

在开启了 TLS 的集群中,每当与集群交互的时候少不了的是身份认证,使用 kubeconfig(即证书) 和 token 两种认证方式是最简单也最通用的认证方式。

kubectl config SUBCOMMAND [options]
kubectl options
      --alsologtostderr[=false]: 同时输出日志到标准错误控制台和文件。
      --api-version="": 和服务端交互使用的API版本。
      --certificate-authority="": 用以进行认证授权的.cert文件路径。
      --client-certificate="": TLS使用的客户端证书路径。
      --client-key="": TLS使用的客户端密钥路径。
      --cluster="": 指定使用的kubeconfig配置文件中的集群名。
      --context="": 指定使用的kubeconfig配置文件中的环境名。
      --insecure-skip-tls-verify[=false]: 如果为true,将不会检查服务器凭证的有效性,
                                          这会导致你的HTTPS链接变得不安全。
      --kubeconfig="": 命令行请求使用的配置文件路径。
      --log-backtrace-at=:0: 当日志长度超过定义的行数时,忽略堆栈信息。
      --log-dir="": 如果不为空,将日志文件写入此目录。
      --log-flush-frequency=5s: 刷新日志的最大时间间隔。
      --logtostderr[=true]: 输出日志到标准错误控制台,不输出到文件。
      --match-server-version[=false]: 要求服务端和客户端版本匹配。
      --namespace="": 如果不为空,命令将使用此namespace。
      --password="": API Server进行简单认证使用的密码。
  -s, --server="": Kubernetes API Server的地址和端口号。
      --stderrthreshold=2: 高于此级别的日志将被输出到错误控制台。
      --token="": 认证到API Server使用的令牌。
      --user="": 指定使用的kubeconfig配置文件中的用户名。
      --username="": API Server进行简单认证使用的用户名。
      --v=0: 指定输出日志的级别。
      --vmodule=: 指定输出日志的模块,格式如下:pattern=N,使用逗号分隔。

 

参考:

1. Kubernetes中文手册  kubernetes中文社区

posted @ 2020-03-05 20:24  yuxi_o  阅读(1359)  评论(0编辑  收藏  举报