Kubectl

Start

install

  • 直接下载安装 kubectl client
# OSX
$ brew insatll kubernetes-cli
  • 下载 binary release,通过这种方式可以下载历史版本的 kubectl
# OSX
$ 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 集群了。

multi cluster config

将多个集群配置添加到config

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

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

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

current-context: "bjidc-test"

将多个集群的配置添加完毕后

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

# 查看集群
$ kubectl config get-contexts
CURRENT   NAME         CLUSTER      AUTHINFO     NAMESPACE
          bjidc-prod   bjidc-prod   bjidc-prod   dlink-prod
*         bjidc-test   bjidc-test   bjidc-test   dlink-test

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

Usages

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

support commands

$ kubectl
$ kubectl -h
$ kubectl --help 

detail command instruction and example

$ 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

# 查看 pod 更详细的信息,所在的节点信息如(IP、NODE、NOMINATED NODE、READINESS、GATES)
$ 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
KIND:     Pod
VERSION:  v1

DESCRIPTION:
     Pod is a collection of containers that can run on a host. This resource is
     created by clients and scheduled onto hosts.

FIELDS:
   apiVersion   <string>
     APIVersion defines the versioned schema of this representation of an
     object. Servers should convert recognized schemas to the latest internal
     value, and may reject unrecognized values. More info:
     https://git.k8s.io/community/contributors/devel/api-conventions.md#resources

   kind <string>
     Kind is a string value representing the REST resource this object
     represents. Servers may infer this from the endpoint the client submits
     requests to. Cannot be updated. In CamelCase. More info:
     https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds

   metadata     <Object>
     Standard object's metadata. More info:
     https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata

   spec <Object>
     Specification of the desired behavior of the pod. More info:
     https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status

   status       <Object>
     Most recently observed status of the pod. This data may not be up to date.
     Populated by the system. Read-only. More info:
     https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status

Basic Command (beginner)

create

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

expose

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

run

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

set

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

Basic Command (Intermediate)

explain

# 查看资源的文档
$ kubectl explain

get

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

edit

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

delete

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

Deploy Commands

rollout

# Manage the rollout of a resource
$ kubectl rollout

scale

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

autoscale

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

Cluster Management Command

certificate

# 修改 certificate 资源
$ kubectl certificate

cluster-info

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

top

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

cordon

# 标记 node 为 unschedulable
$ kubectl cordon

uncordon

# 标记 node 为 schedulable
$ kubectl uncordon

drain

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

taint

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

Troubleshooting and Debugging Commands

describe

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

logs

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

attach

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

exec

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

port-forward

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

proxy

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

cp

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

auth

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

Advanced Commands

apply

# 通过文件名或者标准输入流(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
metadata:
  annotations:
    configmap.reloader.stakater.com/reload: "foo-configmap"
spec:
  template:
    metadata:
...
$ kubectl apply -f https://raw.githubusercontent.com/stakater/Reloader/master/deployments/kubernetes/reloader.yaml

patch

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

replace

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

wait

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

convert

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

Settings Commands

label

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

annotate

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

completion

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

Other Commands

alpha

# Commands for features in alpha
$ kubectl alpha

api-resources

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

api-verisons

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

config

# 修改 kube config 文件,执行该命令会生成 ~/.kube/config 文件
$ kubectl config
# 配置一个名为 default 的集群,并指定服务地址与根证书
$ kubectl config set-cluster default --server=https://192.168.4.111:443 --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>

plugin

# Runs a command-line plugin
$ kubectl plugin

version

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

打赏一个呗

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码支持
扫码打赏,一毛也是爱

打开支付宝扫一扫,即可进行扫码打赏哦