kubectl 常用命令

查看

  • 查看node or pod 的资源消耗
    kubectl top pod -A
    kubectl top node (kubectl describe node xxx 可以详细查看某节点的资源消耗)

  • 查看所有kubelet节点
    kubectl get nodes
    kubectl get nodes -o wide --show-labels //可以看到所有节点的label
    kubectl describe node node-name //查看节点的详细信息,包括资源配置等
    kubectl get all -n kube-system -l k8s-app=kube-dns //根据label查找资源,这里查找kube-system域名下k8s-app标签为kube-dns的所有资源,例如pod、service、deployment等.注意不包括configmap

  • 查看所有pod
    kubectl get pods --all-namespaces
    kubectl get pods -o wide
    kubectl get pods -o wide -w //可以看到实时状态变化
    kubectl get pods -o wide --kubecofig=other-node-kubeconfig.yaml //可以本地查看kubeconfig.yaml指定的集群的信息
    watch "kubectl get pods -n kube-system | grep calico" //只看带关键字calico的容器的实时状态变化
    kubectl get po -n test-system | grep cat | awk '{print $1}' | xargs kubectl delete pod -n test-system //删除指定namespace下的带cat关键字的的所有容器
    kubectl get pods --all-namespaces -o wide |grep -v Running|awk '{system( "kubectl delete pod -n " $1" "$2 " --force")}' //强行删除所有域名下非Running状态的容器

  • 查看pod详情
    kubectl describe pod podname -n namespace
    kubectl get -o json pod podname -n namespace
    kubectl get pods/podname -n namespace
    kubectl get pods/podname -n namespace -o json

  • 查看所有daemonset
    kubectl get daemonset --all-namespaces
    kubectl describe ds calico-node -n kube-system //查看daemonset的日志

  • kubectl get rc,services

  • List one or more resources by their type and names.
    kubectl get rc/web service/frontend pods/web-pod-13je7

  • kubectl get cs
    查看集群基本组件状态

  • kubectl get csr
    查看未授权的 CSR 请求

  • kubectl certificate approve csr-name
    csr请求

  • kubectl get crd
    查看资源

  • kubectl api-resources
    获取所有资源类型

  • 删除具有某些特征的pvc
    kubectl get pvc --all-namespaces -o custom-columns="NAMESPACE:.metadata.namespace,NAME:.metadata.name" --no-headers=true | xargs -n 2 kubectl delete pvc --namespace

修改局部变量

  • kubectl set env ds/calico-node CALICO_IPV4POOL_CIDR=10.210.0.0/24 -n kube-system
  • kubectl set image ds/calico-node calico-node=docker.io/calico/node:v3.18.1 -n kube-system
  • kubectl annotate deployment -n kube-system coredns v1.multus-cni.io/default-network=default/flannel-conf //这条命令是修改deployment资源的annotation, 下面一条是修改deploy里面template的annotation
  • kubectl patch deployment -n kube-system coredns -p '{"spec": {"template":{"metadata":{"annotations":{"v1.multus-cni.io/default-network":"default/flannel-conf"}}}} }'
  • kubectl patch installation default --type='json' -p='[{"op": "replace", "path": "/spec/calicoNetwork/nodeAddressAutodetectionV4", "value": {"cidrs": ["100.200.0.1/24"]}}]'

namespace相关

  • 要使用新的namespace,必须先创建,然后才能写在yaml的metadata的字段里
    kubectl create namespace newname

节点相关

  • kubectl describe node node-name 查看节点所有信息

设置节点不可调度/可调度

  • 计算节点状态为 Ready, 执行 kubectl cordon node-name可致此节点为不可调度
  • 计算节点状态为 Ready,SchedulingDisabled, 执行 kubectl uncordon node-name即可使之成为可调度的节点

节点的label

  • 查看节点的所有label
    kubectl get node --show-labels
  • 给节点添加一个新label
    kubectl label nodes kube-node node=kube-node
  • 修改节点的label
    kubectl label nodes --overwrite k8s-slave node-network-driver=ovs
  • 删除节点的某个label
    kubectl label nodes kube-node node-
  • 给节点添加角色
    kubectl label nodes cluster203-worker-1 node-role.kubernetes.io/worker=
    删除该角色可以使用命令: kubectl label nodes cluster203-worker-1 node-role.kubernetes.io/worker-
  • 根据node的label筛选节点
    kubectl label nodes kube-node node=kube-node
    kubectl label nodes --overwrite k8s-slave node-network-driver=sriov //修改节点k8s-slave的标签node-network-driver的值为sriov
    kubectl get node -a -l "node=kube-node"
    pod或者rc的配置项中添加如下配置,位置跟cotainer平行:
    nodeSelector:
    node: kube-node4
    想把deployment容器调度到指定节点可以使用如下方式:
    • 使用nodeSelector, 增加deployment的yaml,位于spec的子节点,和containers同级:
    nodeSelector:
      kubernetes.io/hostname: 192.168.1.2
    
    • 使用nodeName,添加deployment的yaml,位于Deployment spec节点下面的template节点下面的spec中,和containers同级(跟nodeSelector的位置一样):
       spec:
        serviceAccountName: dev-loki-distributed
        nodeName: cluster-worker-2
        securityContext:
          fsGroup: 101       
        containers:
          - name: nginx
    
  • 让Deployment的各个Pod均匀的分布在各个节点,可以使用如下的Pod 反亲和性,多数情况下需要容忍master节点的不可调度性。topologyKey 是一个用于节点选择的键(key),它表示要考虑的节点标签(labels)的键。在下面的例子中,topologyKey: kubernetes.io/hostname 意味着你想要根据节点的主机名进行调度。
apiVersion: apps/v1
kind: Deployment
metadata:
  name: demo
  namespace: default
spec:
  replicas: 3
  selector:
    matchLabels:
      app: demo
  template:
    metadata:
      labels:
        app: demo
    spec:
      affinity:
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
          - podAffinityTerm:
              labelSelector:
                matchExpressions:
                - key: app
                  operator: In
                  values:
                  - demo
              topologyKey: kubernetes.io/hostname
            weight: 100
      tolerations:
      - effect: NoSchedule
        key: node-role.kubernetes.io/master
        operator: Exists			
      containers:
      - env:
        - name: JAVA_OPTIONS
          valueFrom:
            configMapKeyRef:
              key: java_options
              name: demo-configmap
        image: localhost:5000/demo/demo-service:1.0.0
        imagePullPolicy: IfNotPresent
        name: demo

节点taint 和 容器tolerations

  • 查看某节点的污点可以使用命令 kubectl describe node foo
  • kubectl taint nodes foo dedicated=special-user:NoSchedule 添加或更新节点'foo'的taint,key为'dedicated',value为'special-user',effect为NoSchedule'.
  • kubectl taint nodes foo dedicated:NoSchedule- 删除节点foo的taint,key为dedicated,effect为NoSchedule

    kubectl taint nodes foo dedicated- 删除节点foo的所有key为dedicated的污点
  • 一个污点包含一个key, value, and effect. 示例为 key=value:effect.
  • effect 只能是 NoSchedule, PreferNoSchedule or NoExecute
    有污点的节点,一般pod不会调度上去,但是如果pod能够容忍这个污点就会调度上去,这就是pod的tolerations(taint是节点的属性,tolerations是pod的属性).
    如下在PodSpec中定义了toleration,该tolerations完全匹配taint那么该pod就可以被调度到此节点:
tolerations:
- key: "key"
  operator: "Equal"
  value: "value"
  effect: "NoSchedule"

tolerations:
- key: "key"
  operator: "Exists"
  effect: "NoSchedule"

官方指导https://kubernetes.io/docs/concepts/configuration/taint-and-toleration/
kubectl cordon node命令使某个节点不可调度其实就是给该节点配置了如下污点:

# kubectl describe node cluster155-master-1 |grep Taint -A 2
Taints:             node.kubernetes.io/unschedulable:NoSchedule
Unschedulable:      true

如果想让容器仍然能调度到该节点需要配置如下容忍:

      tolerations:
        - key: "node.kubernetes.io/unschedulable"
          operator: "Exists"
          effect: "NoSchedule"

另外,cordon的节点对daemonset的容器是不生效的,daemonset的容器仍然能调度到cordon的节点。去查看daemonset的容器描述可以看到如下容忍:

Tolerations:     node-role.kubernetes.io/master:NoSchedule
                 node.kubernetes.io/disk-pressure:NoSchedule op=Exists
                 node.kubernetes.io/memory-pressure:NoSchedule op=Exists
                 node.kubernetes.io/network-unavailable:NoSchedule op=Exists
                 node.kubernetes.io/not-ready:NoExecute op=Exists
                 node.kubernetes.io/pid-pressure:NoSchedule op=Exists
                 node.kubernetes.io/unreachable:NoExecute op=Exists
                 node.kubernetes.io/unschedulable:NoSchedule op=Exists

正因为如此,daemonset的容器仍然能调度到cordon的节点。

  • 驱逐指定节点上的 pod 并隔离节点,常用于节点的升级
    kubectl drain --delete-emptydir-data --force --ignore-daemonsets <NODE_NAME>

yaml文件、配置相关

  • 查看资源的yaml
    kubectl get deploy/my-nginx -o yaml
    kubectl get deploy/my-nginx -o yaml > example.yaml

  • 生成yaml文件
    由于yaml文件格式不好记住,可以先通过kubectl命令生成yaml,再更改yaml。 –dry-run表示尝试,不真实执行。
    kubectl run --image=nginx my-nginx -o yaml --dry-run >> xxx.yaml

  • 修改API 资源的属性
    kubectl edit pod/testnew2-prd-123 -n testnew2

    //Update a container's image; spec.containers[*].name is required because it's a merge key.
    kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}'

    //Update a single-container pod's image version (tag) to v4
    kubectl get pod mypod -o yaml | sed 's/(image: myimage):.*$/\1:v4/' | kubectl replace -f -

  • 解释资源详细信息,命令可能会显示旧的group/version,我们可以通过--api-version参数显示设置
    不知道该如何编写YAML文件的时候,或者看到一个资源不知道字段是何含义,就可以使用改命令来帮助我们获得更多提示信息。
    kubectl explain replicaset --api-version apps/v1

  • 不创建文件直接创建资源

cat <<EOF | kubectl create -f -
apiVersion: "k8s.cni.cncf.io/v1"
kind: NetworkAttachmentDefinition
metadata:
  name: flannel-conf
spec: 
  config: '{
    "cniVersion": "0.3.0",
    "type": "flannel",
    "delegate": {
      "isDefaultGateway": true
    }
  }'
EOF  

对容器执行命令

  • 对单容器的pod执行命令,注意--后面必须有空格(以在容器内执行命令ip a为例)
    kubectl exec -it pod_name -n namespace -- ip a

    有的时候一个pod中有多个容器,只有针对整个pod的命令才有效,此时需要指定container,这里指定的是container-name(可以用kubectl describe pod查看所有的容器名称)
    kubectl exec -it podname -n namespace -c containername -- ip a

  • 强制删除pod
    kubectl delete pod podname -n namespace --force --grace-period=0

  • 文件拷贝, 如下格式把容器中指定目录的文件拷贝到本地磁盘指定目录
    kubectl cp pod-name:/path/to/file /tmp/localpath/file

  • 修改容器的镜像,如下是修改daemonset contiv-netplugin-ovs contiv-netplugin的镜像为新镜像,首先要先docker pull新镜像

    • kubectl set image ds/contiv-netplugin-ovs contiv-netplugin=new-image -n kube-system
      然后需要删除需要更新的daemonset中的pod,然后会重建pod,这个pod使用的就是新镜像. 这里的标签是container-name=new-image-name
  • 动态调整副本数

    • kubectl scale deployment.v1.apps/apitest-deployment --replicas=10 -n namespace
  • 查看pod的log

    • kubectl log -n namespace pod-name
    • 如果pod里有多个容器,需要制定容器名来查看log: kubectl log -n namespace pod-name container-1-name
    • 如果容器panic后重启,想查看panic日志,需要查看上一个容器的log: kubectl logs --previous podname -n namespace

稍复杂点的命令

  • 打印交互的过程
    kubectl get ns -v=9

  • 按状态筛选容器以及删除
    kubectl get pods --all-namespaces --field-selector status.phase=Pending -o json |
    jq '.items[] | "kubectl delete pods (.metadata.name) -n (.metadata.namespace)"' |
    xargs -n 1 bash -c

  • kubectl get pods --all-namespaces --field-selector status.phase=Pending -o json 根据标签选择容器
  • jq '.items[] | "kubectl delete pods (.metadata.name) -n (.metadata.namespace)"' 把筛选出来的信息编辑成指定的字符串格式
  • xargs -n 1 bash -c 执行每一条命令
  • 删除单个NS下面的一些pods
    kubectl -n default get pods | grep Completed | awk '{print $1}' | xargs kubectl -n default delete pods

最后,查询命令使用方法的终极大招就是help手册和man手册, 但kubectl 没有man手册,只能通过kubectl --help来查看,仔细阅读,多尝试就可以啦。

posted @ 2019-07-17 20:15  JaneySJ  阅读(8705)  评论(0编辑  收藏  举报