栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

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

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

目录
  • 概述
    • 语法
    • 资源类型
    • 输出选项
  • 实战
    • 基本命令
      • create
      • get
      • edit
      • delete
    • 集群管理
      • cluster-info
      • top
      • cordon && uncordon
      • drain
      • taint
    • 高级命令
      • apply
      • replace
    • 故障诊断和调试
      • describe
      • logs
      • exec
    • 设置命令
      • label
    • 其他命令
      • version
  • 参考


概述 语法
kubectl [command] [TYPE] [NAME] [flags]
  • command: 指定要对资源执行的操作,例如,create、get、describe和delete
  • type: 指定资源类型,资源类型不区分大小写, 可以指定单数、复数或缩写形式。
  • name:指定资源的名称,名称区分大小写。 如果省略名称,则显示所有资源的详细信息。
  • flags:指定可选的参数。例如,可用-s 或者–server 参数指定 Kubernetes API server 的地址和端口。

-h查看所有命令

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:
  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  --help" for more information about a given command.
Use "kubectl options" for a list of global command-line options (applies to all commands).

之后实战的分类,就大致按照帮助命令的分类进行展示了。
再看下选项

The following options can be passed to any command:
      --add-dir-header=false: If true, adds the file directory to the header
      --alsologtostderr=false: log to standard error as well as files
      --as='': Username to impersonate for the operation
      --as-group=[]: Group to impersonate for the operation, this flag can be repeated to specify multiple groups.
      --cache-dir='/root/.kube/http-cache': Default HTTP cache directory
      --certificate-authority='': Path to a cert file for the certificate authority
      --client-certificate='': Path to a client certificate file for TLS
      --client-key='': Path to a client key file for TLS
      --cluster='': The name of the kubeconfig cluster to use
      --context='': The name of the kubeconfig context to use
      --insecure-skip-tls-verify=false: If true, the server's certificate will not be checked for validity. This will
make your HTTPS connections insecure
      --kubeconfig='': Path to the kubeconfig file to use for CLI requests.
      --log-backtrace-at=:0: when logging hits line file:N, emit a stack trace
      --log-dir='': If non-empty, write log files in this directory
      --log-file='': If non-empty, use this log file
      --log-file-max-size=1800: Defines the maximum size a log file can grow to. Unit is megabytes. If the value is 0,
the maximum file size is unlimited.
      --log-flush-frequency=5s: Maximum number of seconds between log flushes
      --logtostderr=true: log to standard error instead of files
      --match-server-version=false: Require server version to match client version
  -n, --namespace='': If present, the namespace scope for this CLI request
      --password='': Password for basic authentication to the API server
      --profile='none': Name of profile to capture. One of (none|cpu|heap|goroutine|threadcreate|block|mutex)
      --profile-output='profile.pprof': Name of the file to write the profile to
      --request-timeout='0': The length of time to wait before giving up on a single server request. Non-zero values
should contain a corresponding time unit (e.g. 1s, 2m, 3h). A value of zero means don't timeout requests.
  -s, --server='': The address and port of the Kubernetes API server
      --skip-headers=false: If true, avoid header prefixes in the log messages
      --skip-log-headers=false: If true, avoid headers when opening log files
      --stderrthreshold=2: logs at or above this threshold go to stderr
      --token='': Bearer token for authentication to the API server
      --user='': The name of the kubeconfig user to use
      --username='': Username for basic authentication to the API server
  -v, --v=0: number for the log level verbosity
      --vmodule=: comma-separated list of pattern=N settings for file-filtered logging

经常用的是–cluster指定集群,-n指定命名空间

资源类型
kubectl api-resources
资源名缩写名API 分组按命名空间资源类型
bindingstrueBinding
componentstatusescsfalseComponentStatus
configmapscmtrueConfigMap
endpointseptrueEndpoints
eventsevtrueEvent
limitrangeslimitstrueLimitRange
namespacesnsfalseNamespace
nodesnofalseNode
persistentvolumeclaimspvctruePersistentVolumeClaim
persistentvolumespvfalsePersistentVolume
podspotruePod
podtemplatestruePodTemplate
replicationcontrollersrctrueReplicationController
resourcequotasquotatrueResourceQuota
secretstrueSecret
serviceaccountssatrueServiceAccount
servicessvctrueService
mutatingwebhookconfigurationsadmissionregistration.k8s.iofalseMutatingWebhookConfiguration
validatingwebhookconfigurationsadmissionregistration.k8s.iofalseValidatingWebhookConfiguration
customresourcedefinitionscrd,crdsapiextensions.k8s.iofalseCustomResourceDefinition
apiservicesapiregistration.k8s.iofalseAPIService
controllerrevisionsappstrueControllerRevision
daemonsetsdsappstrueDaemonSet
deploymentsdeployappstrueDeployment
replicasetsrsappstrueReplicaSet
statefulsetsstsappstrueStatefulSet
tokenreviewsauthentication.k8s.iofalseTokenReview
localsubjectaccessreviewsauthorization.k8s.iotrueLocalSubjectAccessReview
selfsubjectaccessreviewsauthorization.k8s.iofalseSelfSubjectAccessReview
selfsubjectrulesreviewsauthorization.k8s.iofalseSelfSubjectRulesReview
subjectaccessreviewsauthorization.k8s.iofalseSubjectAccessReview
horizontalpodautoscalershpaautoscalingtrueHorizontalPodAutoscaler
cronjobscjbatchtrueCronJob
jobsbatchtrueJob
certificatesigningrequestscsrcertificates.k8s.iofalseCertificateSigningRequest
leasescoordination.k8s.iotrueLease
endpointslicesdiscovery.k8s.iotrueEndpointSlice
eventsevevents.k8s.iotrueEvent
ingressesingextensionstrueIngress
flowschemasflowcontrol.apiserver.k8s.iofalseFlowSchema
prioritylevelconfigurationsflowcontrol.apiserver.k8s.iofalsePriorityLevelConfiguration
ingressclassesnetworking.k8s.iofalseIngressClass
ingressesingnetworking.k8s.iotrueIngress
networkpoliciesnetpolnetworking.k8s.iotrueNetworkPolicy
runtimeclassesnode.k8s.iofalseRuntimeClass
poddisruptionbudgetspdbpolicytruePodDisruptionBudget
podsecuritypoliciespsppolicyfalsePodSecurityPolicy
clusterrolebindingsrbac.authorization.k8s.iofalseClusterRoleBinding
clusterrolesrbac.authorization.k8s.iofalseClusterRole
rolebindingsrbac.authorization.k8s.iotrueRoleBinding
rolesrbac.authorization.k8s.iotrueRole
priorityclassespcscheduling.k8s.iofalsePriorityClass
csidriversstorage.k8s.iofalseCSIDriver
csinodesstorage.k8s.iofalseCSINode
storageclassesscstorage.k8s.iofalseStorageClass
volumeattachmentsstorage.k8s.iofalseVolumeAttachment

资源名的缩写大家还是要记一下,之后的文章敲命令我也会多用缩写。常用的有:

  • cm:ConfigMap
  • ns:NameSpace
  • no:Node
  • pvc:PersistentVolumeClaim
  • pv:PersistentVolume
  • po:Pod
  • rc:ReplicationController
  • sa:ServiceAccount
  • svc:Service
  • ds:DaemonSet
  • deploy:Deployment
  • rs:ReplicaSet
  • sts:StatefulSet
  • cj:CronJob
输出选项
kubectl [command] [TYPE] [NAME] -o=
Output formatDescription
-o custom-columns=使用逗号分隔的自定义列列表打印表。
-o custom-columns-file=使用 文件中的自定义列模板打印表。
-o json输出 JSON 格式的 API 对象
-o jsonpath=