[root@master ~]# kubectl -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 #基于rc svc  depoy或创建svc资源
  run           Run a particular image on the cluster  #通过创建deploy在集群中运行指定的镜像
  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  #基于文件名、stdin、资源或名字、以及资源和选择器删除资源

Deploy Commands:   #部署命令
  rollout       Manage the rollout of a resource     #管理资源的滚动更新
  scale         Set a new size for a Deployment, ReplicaSet or Replication Controller #伸缩deploy、rs、rc或job的规模
  autoscale     Auto-scale a Deployment, ReplicaSet, or ReplicationController    #伸缩deploy、rs、rc进行自动伸缩

Cluster Management Commands:   #集群管理命令
  certificate   Modify certificate resources.   #配置数字证书资源
  cluster-info  Display cluster info            #打印集群信息
  top           Display Resource (CPU/Memory/Storage) usage.  #打印资源(cpu/mem/storage)使用率
  cordon        Mark node as unschedulable   #将node设定为 不可用unschedulable状态
  uncordon      Mark node as schedulable     #将node设定为 不可用schedulable状态
  drain         Drain node in preparation for maintenance  #排干指定的node的负载以进入维护模式
  taint         Update the taints on one or more nodes     #为node声明污点及标准行为

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                    #显示一个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 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    #基于文件或stdin将配置应用于资源
  patch         Update field(s) of a resource using strategic merge patch   #使用策略合并补丁更新资源字段
  replace       Replace a resource by filename or stdin                     #基于文件或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.

Settings Commands:   #设置命令
  label         Update the labels on a resource       #更新指定资源的label
  annotate      Update the annotations on a resource  #更新资源的annotation
  completion    Output shell completion code for the specified shell (bash or zsh) #输出指定的shell的补全代码

Other Commands:   #其他命令
  alpha         Commands for features in alpha
  api-resources Print the supported API resources on the server  #打印服务器上支持的API资源
  api-versions  Print the supported API versions on the server, in the form of "group/version" #以 group/version格式打印服务器支持的API版本信息
  config        Modify kubeconfig files                            #配置kubeconfig文件的内容
  plugin        Provides utilities for interacting with plugins.   #运行命令行插件
  version       Print the client and server version information    #打印服务端和客户端的版本信息

  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).

三、kubectl get命令的常用输出格式

1、kubectl get命令的常用输出格式

[root@master ~]# kubectl get -h
Display one or many resources
  # List all pods in ps output format.
  kubectl get pods
  # List all pods in ps output format with more information (such as node name).
  kubectl get pods -o wide    #显示资源的详细信息
  # List a single replication controller with specified NAME in ps output format.
  kubectl get replicationcontroller web
  # List deployments in JSON output format, in the "v1" version of the "apps" API group:
  kubectl get deployments.v1.apps -o json  #JSON格式输出API对象信息
  # List a single pod in JSON output format.
  kubectl get -o json pod web-pod-13je7
  # List a pod identified by type and name specified in "pod.yaml" in JSON output format.
  kubectl get -f pod.yaml -o json   #JSON格式输出API对象信息
  # List resources from a directory with kustomization.yaml - e.g. dir/kustomization.yaml.
  kubectl get -k dir/
  # Return only the phase value of the specified pod.
  kubectl get -o template pod/web-pod-13je7 --template={{.status.phase}}
  # List resource information in custom columns.
  kubectl get pod test-pod -o custom-columns=CONTAINER:.spec.containers[0].name,IMAGE:.spec.containers[0].image
  # List all replication controllers and services together in ps output format.
  kubectl get rc,services
  # List one or more resources by their type and names.
  kubectl get rc/web service/frontend pods/web-pod-13je7

  -o, --output='': Output format. One of:
See custom columns [http://kubernetes.io/docs/user-guide/kubectl-overview/#custom-columns], golang template
[http://golang.org/pkg/text/template/#pkg-overview] and jsonpath template
      --output-watch-events=false: Output watch event objects when --watch or --watch-only is used. Existing objects are

2、kubectl 通用选项

[root@master ~]# kubectl options 
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
      --tls-server-name='': Server name to use for server certificate validation. If it is not provided, the hostname
used to contact the server is used
      --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




[root@master ~]# kubectl get ns
NAME              STATUS   AGE
default           Active   41h
ingress-nginx     Active   33h
kube-node-lease   Active   41h
kube-public       Active   41h
kube-system       Active   41h


[root@master ~]# kubectl describe ns default 
Name:         default
Labels:       <none>
Annotations:  <none>
Status:       Active

No resource quota.

No LimitRange resource.


[root@master ~]# kubectl get pods -n kube-system 
NAME                              READY   STATUS    RESTARTS   AGE
coredns-66bff467f8-d9xjc          1/1     Running   0          41h
coredns-66bff467f8-lvldb          1/1     Running   0          41h
etcd-master                       1/1     Running   0          41h
kube-apiserver-master             1/1     Running   0          41h
kube-controller-manager-master    1/1     Running   0          41h
kube-flannel-ds-amd64-5zsxg       1/1     Running   0          33h
kube-flannel-ds-amd64-kmsb5       1/1     Running   0          33h
kube-flannel-ds-amd64-lzh2b       1/1     Running   0          33h
kube-proxy-lg58q                  1/1     Running   0          41h
kube-proxy-qcztn                  1/1     Running   0          41h
kube-proxy-rf6fz                  1/1     Running   0          41h
kube-scheduler-master             1/1     Running   0          41h
metrics-server-79c86dd576-6h2b7   1/1     Running   0          33




[root@master chapter3]# kubectl apply -f namespace-example.yaml 
namespace/dev created


[root@master ~]# kubectl create ns luoahong
namespace/luoahong created







[root@master chapter3]# kubectl create -f pod-example.yaml 
pod/pod-example created


[root@master chapter3]# kubectl get -f pod-example.yaml 
pod-example   1/1     Running   0          40s

[root@master chapter3]# kubectl get -f pod-example.yaml -o custom-columns=NMAE:metadata.name,STATUS:status.phase
NMAE          STATUS
pod-example   Running

[root@master chapter3]# kubectl describe -f pod-example.yaml 
Name:         pod-example
Namespace:    default
Priority:     0
Node:         node2/
Start Time:   Wed, 05 Aug 2020 17:12:48 +0800
Labels:       <none>
Annotations:  <none>
Status:       Running
    Container ID:   docker://fc64d4153a6a5bb315fc1669c6cdcbf4ad37ce1541eb655ba1bc62919b50f5db
    Image:          ikubernetes/myapp:v2
    Image ID:       docker-pullable://ikubernetes/myapp@sha256:85a2b81a62f09a414ea33b74fb8aa686ed9b168294b26b4c819df0be0712d358
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Wed, 05 Aug 2020 17:13:06 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-pwl2t (ro)
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-pwl2t
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
  Type    Reason     Age    From               Message
  ----    ------     ----   ----               -------
  Normal  Pulling    3m7s   kubelet, node2     Pulling image "ikubernetes/myapp:v2"
  Normal  Scheduled  3m6s   default-scheduler  Successfully assigned default/pod-example to node2
  Normal  Pulled     2m51s  kubelet, node2     Successfully pulled image "ikubernetes/myapp:v2"
  Normal  Created    2m50s  kubelet, node2     Created container myapp
  Normal  Started    2m50s  kubelet, node2     Started container myapp


[root@master chapter3]# kubectl get pods pod-example -o yaml > pod-exaple-update.yaml
[root@master chapter3]# sed -i 's@\(image:\).*@ikubernetes/myapp:v2@' pod-exaple-update.yaml 
[root@master chapter3]# kubectl replace -f pod-exaple-update.yaml
pod/pod-example created replaces




[root@master chapter3]# kubectl delete -f pod-example.yaml 
pod "pod-example" deleted
[root@master chapter3]# kubectl get -f pod-example.yaml 
Error from server (NotFound): pods "pod-example" not found





[root@master chapter3]# kubectl apply -f pod-example.yaml 
pod/pod-example created



[root@master chapter3]# vim pod-example.yaml 
把image: ikubernetes/myapp:v1修改image: ikubernetes/myapp:v2
[root@master chapter3]# kubectl apply -f pod-example.yaml 
pod/pod-example configured


kubectl apply -f pod_example.yaml --prune -l <labels>


那些不存在相应定义的资源对象讲被删除、因此、删除资源对象的操作依然建议使用陈述式、对象配置方式的命令:#kubectl delete 进行,这样的命令格式操作目标明确且不易出现偏差

posted @ 2020-08-06 05:34  活的潇洒80  阅读(124)  评论(0编辑  收藏