kubectl 安装

Install and Set Up kubectl


  • 直接下载安装 kubectl client
$ brew insatll kubernetes-cli
  • 下载 binary release,通过这种方式可以下载历史版本的 kubectl
$ curl -LO https://storage.googleapis.com/kubernetes-release/release/v1.11.0/bin/darwin/amd64/kubectl

# Linux
$ curl -LO https://storage.googleapis.com/kubernetes-release/release/v1.11.0/bin/linux/amd64/kubectl

# 添加执行权限
$ sudo chmod +x ./kubectl

# 移动到 PATH
$ sudo mv ./kubectl /usr/local/bin/

配置 config

kubectl 默认使用~/.kube/config文件作为做连接 kubernetes 集群的配置文件,你可以在 kubernetes server master 的~/.kube/config找到它,他是集群管理员角色的 config。当然也可以创建其他角色(权限的)config。

然后将对应的config文件放到 client 节点的~/.kube下,然后就可以通过kubectl来访问和管理 kubernetes 集群了。



apiVersion: v1
kind: Config
- name: "bjidc-test"
    server: "https://rancher.example.com/k8s/clusters/c-t5mbq"
- name: "bjidc-prod"
    server: "https://rancher.example.com/k8s/clusters/c-krfhf"

- name: "bjidc-test"
    token: "kubeconfig-u-xxxxxxxx:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
- name: "bjidc-prod"
    token: "kubeconfig-u-xxxxxxxx:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

- name: "bjidc-test"
    user: "bjidc-test"
    cluster: "bjidc-test"
    namespace: dlink-test
- name: "bjidc-prod"
    user: "bjidc-prod"
    cluster: "bjidc-prod"
    namespace: dlink-prod

current-context: "bjidc-test"


# 查看合并后的 config
$ kubectl config view

# 查看集群
$ kubectl config get-contexts
          bjidc-prod   bjidc-prod   bjidc-prod   dlink-prod
*         bjidc-test   bjidc-test   bjidc-test   dlink-test

# 切换集群
$ kubectl config use-context bjidc-prod

查看 kubectl 帮助


# kubectl action resource
$ kubectl [flags] [options]

查看 kubectl 命令支持的所有 command

$ kubectl
$ kubectl -h
$ kubectl --help 

查看具体 command 的使用说明和示例

$ kubectl <command>
$ kubectl <command> -h
$ kubectl <command> --help

# 例如
$ kubectl get -h
$ kubectl get nodes --help

a list of global command-line options (applies to all commands)

$ kubectl options
The following options can be passed to any command:

      --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='C:\Users\zhangqiang\.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

Common Options

$ kubectl get <type of resource>

# 在使用 kubectl 时,指定 --kubeconfig 可以指定配置文件,不指定则默认使用 ~/.kube/config 文件
$ kubectl get pods --kubeconfig ./myconfig

$ kubectl get pod <pod_name> -o wide

# 查看以 yaml 格式查看 resouce 所有定义
$ kubectl get pod <pod_name> -o yaml

Use “kubectl api-resources” for a complete list of supported resources.

$ kubectl api-resources
* all  
* certificatesigningrequests (aka 'csr')  
* clusterrolebindings  
* clusterroles  
* componentstatuses (aka 'cs')  
* configmaps (aka 'cm')  
* controllerrevisions  
* cronjobs  
* customresourcedefinition (aka 'crd')  
* daemonsets (aka 'ds')  
* deployments (aka 'deploy')  
* endpoints (aka 'ep')  
* events (aka 'ev')  
* horizontalpodautoscalers (aka 'hpa')  
* ingresses (aka 'ing')  
* jobs  
* limitranges (aka 'limits')  
* namespaces (aka 'ns')  
* networkpolicies (aka 'netpol')  
* nodes (aka 'no')  
* persistentvolumeclaims (aka 'pvc')  
* persistentvolumes (aka 'pv')  
* poddisruptionbudgets (aka 'pdb')  
* podpreset  
* pods (aka 'po')  
* podsecuritypolicies (aka 'psp')  
* podtemplates  
* replicasets (aka 'rs')  
* replicationcontrollers (aka 'rc')  
* resourcequotas (aka 'quota')  
* rolebindings  
* roles  
* secrets  
* serviceaccounts (aka 'sa')  
* services (aka 'svc')  
* statefulsets (aka 'sts')  
* storageclasses (aka 'sc')

Use “kubectl explain " for a detailed description of that resource (e.g. kubectl explain pods).

$ kubectl explain pods

Basic Command (beginner)

# Create a resource from a file or from stdin.
$ kubectl create

# 使用 replication controller, service, deployment 或者 pod 并暴露它作为一个新的 Kubernetes Service
$ kubectl expose

# 在集群中运行一个指定的镜像
$ kubectl run

# 为 objects 设置一个指定的特征
$ kubectl set

Basic Command (Intermediate)

# 查看资源的文档
$ kubectl explain

# 显示一个或更多 resources
$ kubectl get

# 在服务器上编辑一个 resource
$ kubectl edit

# Delete resources by filenames, stdin, resources and names, or by resources and label selector
$ kubectl delete

Deploy Commands

# Manage the rollout of a resource
$ kubectl rollout

# 为 deployment, replicaset, replication controller 或者 Job 设置一个新的副本数量
$ kubectl scale

# 自动调整一个 deployment, replicaset, 或者 replication controller 的副本数量
$ kubectl autoscale

Cluster Management Command

# 修改 certificate 资源
$ kubectl certificate

# 显示集群信息
$ kubectl cluster-info

# Display Resource (CPU/Memory/Storage) usage.
$ kubectl top

# 标记 node 为 unschedulable
$ kubectl cordon

# 标记 node 为 schedulable
$ kubectl uncordon

# drain node in preparation for maintenance(排除节点准备维护)
$ kubectl drain

# 更新一个或者多个 nodes 上的 taints(污点?)
$ kubectl taint

Troubleshooting and Debugging Commands

# 显示一个指定 resource 或者 group 的 resources 详情
$ kubectl describe
# 例如查看 pod name 为 abc 的详细信息
$ kubectl describe pod abc

# 输出容器在 pod 的日志
$ kubectl logs

# attach 到一个运行中的 container
$ kubectl attach

# 在一个 container 中执行一个命令
$ kubectl exec

# 转发一个或多个本子端口到 pod
$ kubectl port-forward

# 运行一个 proxy 到 kubernetes API server
$ kubectl proxy

# 复制 files 和 directories 到 containers 和从 containers 复制 files 和 directories
$ kubectl cp

# inspect authorization(检查授权)
$ kubectl auth

Advanced Commands

# 通过文件名或者标准输入流(stdin)对资源进行配置
$ kubectl apply
# 使用 Reloader - A Kubernetes controller to watch changes in ConfigMap and Secrets and then restart pods for 
# Deployment, StatefulSet, DaemonSet and DeploymentConfig
# 参考链接 https://github.com/stakater/Reloader
kind: Deployment
    configmap.reloader.stakater.com/reload: "foo-configmap"
$ kubectl apply -f https://raw.githubusercontent.com/stakater/Reloader/master/deployments/kubernetes/reloader.yaml

# 使用 strategic merge patch 更新一个资源的 field(s)
$ kubectl patch

# 通过 filename 或者 stdin 替换一个资源
$ kubectl replace

# Experimental: Wait for one condition on one or many resources
$ kubectl wait

# 在不同的 API versions 转换配置文件
$ kubectl convert

Settings Commands

# 更新在这个资源上的 labels
$ kubectl label

# 更新一个资源的注解
$ kubectl annotate

# Output shell completion code for the specified shell (bash or zsh)
$ kubectl completion

Other Commands

# Commands for features in alpha
$ kubectl alpha

# Print the supported API resources on the server
$ kubectl api-resources

# Print the supported API versions on the server, in the form of "group/version"
$ kubectl api-verisons

# 修改 kube config 文件,执行该命令会生成 ~/.kube/config 文件
$ kubectl config
# 配置一个名为 default 的集群,并指定服务地址与根证书
$ kubectl config set-cluster default --server= --certificate-authority=${PWD}/ssl/ca.pem
# 设置一个管理用户为 admin,并配置访问证书
$ kubectl config set-credentials admin --certificate-authority=${PWD}/ssl/ca.pem --client-key=${PWD}/ssl/admin-key.pem --client-certificate=${PWD}/ssl/admin.pem
# 设置一个名为 default 使用 default 集群与 admin 用户的上下文,
$ kubectl config set-context default --cluster=default --user=admin
# 启用 default 为默认上下文
$ kubectl config use-context default

# 设置修改当前的 namespace,这样就不用每次执行命令的时候加 --namespace 参数了
$ kubectl config set-context --current --namespace=<insert-namespace-name-here>

# Runs a command-line plugin
$ kubectl plugin

# 输出 client 和 server 的版本信息
$ kubectl version