kubectl詳解


kubectl是目前管理k8s集群的最強利器.所有對集群的控制和管理都可以通個kubectl進行.

通過kubectl --help查看幫助信息。 

更多信息請訪問: https://kubernetes.io/docs/reference/kubectl/overview/

基本命令(初級):
  create         創建一個新的資源從一個文件或者stdin
  expose         獲取replication controller,service,deployment和pod,並將其作為一個新的服務.
  
  run            在集群內運行特定鏡像.
  set            在對象上設置特定功能
  run-container  在集群上運行特定鏡像,已被run替代

基本命令(中級):
  get            現實一個或多個資源
  explain        資源文檔
  edit           編輯服務器上的資源
  delete         按照文件名稱,標准輸入,資源和名稱來刪除資源,還可以通過資源和標簽選擇器

部署命令:
  rollout        管理資源的部署
  rolling-update 執行給定的ReplicationController的滾動更新
  scale          為Deployment,ReplicaSet,Replication等控制器設置一個新的大小或者任務
  autoscale      自動擴展 Deployment, ReplicaSet, 或 ReplicationController

集群管理命令:
  certificate    修改證書資源
  cluster-info   顯示集群信息
  top            顯示資源 (CPU/Memory/Storage)使用情況
  cordon         將節點標記為不可調度
  uncordon       將節點標記為可調度
  drain          節點准備維護
  taint          更新一個或多個節點上的錯誤

故障排除與調試命令:
  describe       顯示特定資源或資源組的詳細信息
  logs           打印pod中容器的日志
  attach         進入正在運行的容器
  exec           在容器中執行命令
  port-forward   將一個或多個本地端口轉發到pod
  proxy          運行代理到kubernetes的API Server
  cp             從容器中復制一個文件或者目錄
  auth           檢查授權
  
高級命令:
  apply          通過filename或stdin將配置應用到資源
  patch          更新資源的字段,通過策略合並
  replace        用filename或stdin替換資源
  convert        在不同的API版本之間轉換配置文件

配置命令:
  label          為資源更新標簽
  annotate       為資源更新注釋
  completion     輸出指定shell的shell代碼(bash or zsh)

其它命令:
  api-versions   輸出服務器支持的API版本
  config         修改kubeconfig配置文件
  help           查看幫助信息
  plugin         運行命令行插件
  version        打印客戶端和服務端的版本信息

當然也可以通過   kubectl config --help類似命令查看子命令:

修改kubeconfig文件中的數據.

The loading order follows these rules: 

  1. If the --kubeconfig flag is set, then only that file is loaded.  The flag
may only be set once and no merging takes place.  
  2. If $KUBECONFIG environment variable is set, then it is used a list of paths
(normal path delimitting rules for your system).  These paths are merged.  When
a value is modified, it is modified in the file that defines the stanza.  When a
value is created, it is created in the first file that exists.  If no files in
the chain exist, then it creates the last file in the list.  
  3. Otherwise, ${HOME}/.kube/config is used and no merging takes place.

可用命令:
  current-context 顯示當前contexts
  delete-cluster  從kubeconfig中刪除指定的集群
  delete-context  從kubeconfig中刪除指定的上下文
  get-clusters    顯示kubeconfig中定義的集群
  get-contexts    描述一個或多個contexts
  rename-context  在kubeconfig中給一個context改名
  set             在kubeconfig中設置單個值
  set-cluster     在kubeconfig中設置一個集群
  set-context     在kubeconfig中設置一個context
  set-credentials 在kubeconfig中設置一個用戶
  unset           取消設置
  use-context     在kubeconfig中設置current-context
  view            顯示合並后的kubeconfig設置或指定kubeconfig文件

 

kubectl的命令可以分為三類:

1.集群訪問配置:kubectl config

配置kubectl管理的kubernetes集群的配置信息,與Linux中的命令行不同的是,命令行的設置直接操控文件.

(1)kubectl config view:查看當前節點的kubeconfig配置信息.

kubernetes可以有多個集群,一個集群又可以配置無數過service,多層級有利於梳理計算機資源。

打印文件的內容,密鑰數據省略.

root@VM-16-6-ubuntu:~# cat /etc/kubernetes/admin.conf 
apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: ...
    server: https://148.70.251.10:6443
  name: kubernetes
contexts:
- context:
    cluster: kubernetes
    user: kubernetes-admin
  name: kubernetes-admin@kubernetes
current-context: kubernetes-admin@kubernetes
kind: Config
preferences: {}
users:
- name: kubernetes-admin
  user:
    client-certificate-data: ...
    client-key-data: ...

通過kubectl config view可以查看的相同的信息.

root@VM-16-6-ubuntu:~# kubectl config view
apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: REDACTED
    server: https://148.70.251.10:6443
  name: kubernetes
contexts:
- context:
    cluster: kubernetes
    user: kubernetes-admin
  name: kubernetes-admin@kubernetes
current-context: kubernetes-admin@kubernetes
kind: Config
preferences: {}
users:
- name: kubernetes-admin
  user:
    client-certificate-data: REDACTED
    client-key-data: REDACTED

(2)kubectl config set-cluster:添加集群

root@VM-16-6-ubuntu:~# kubectl config set-cluster k8s1 --server=https://1.2.3.4
Cluster "k8s1" set.

 查看配置文件:

root@VM-16-6-ubuntu:~# head -5 /etc/kubernetes/admin.conf 
apiVersion: v1
clusters:
- cluster:
    server: https://1.2.3.4
  name: k8s1

確認已經寫入了配置文件.

root@VM-16-6-ubuntu:~# kubectl config view
apiVersion: v1
clusters:
- cluster:
    server: https://1.2.3.4
  name: k8s1
- cluster:
    certificate-authority-data: REDACTED
    server: https://148.70.251.10:6443
  name: kubernetes
contexts:
- context:
    cluster: kubernetes
    user: kubernetes-admin
  name: kubernetes-admin@kubernetes
current-context: kubernetes-admin@kubernetes
kind: Config
preferences: {}
users:
- name: kubernetes-admin
  user:
    client-certificate-data: REDACTED
    client-key-data: REDACTED

(3)kubectl config get-clusters:查看kubeconfig中所有的cluster

root@VM-16-6-ubuntu:~# kubectl config get-clusters
NAME
k8s1
kubernetes

(4)kubectl config delete-cluster:刪除某個cluster

root@VM-16-6-ubuntu:~# kubectl config delete-cluster k8s1
deleted cluster k8s1 from /etc/kubernetes/admin.conf
root@VM-16-6-ubuntu:~# kubectl config get-clusters
NAME
kubernetes

(5)kubectl config get-context:獲取所有的context

kubernetes中context類似“用戶”的意思,這是多租戶使用的的前提。

root@VM-16-6-ubuntu:~# kubectl config current-context
kubernetes-admin@kubernetes

(6)kubectl config set-context:添加一個context

root@VM-16-6-ubuntu:~# kubectl config set-context admin1@k8s1 --user=admin1
Context "admin1@k8s1" created.
root@VM-16-6-ubuntu:~# kubectl config get-contexts
CURRENT   NAME                          CLUSTER      AUTHINFO           NAMESPACE
          admin1@k8s1                                admin1             
*         kubernetes-admin@kubernetes   kubernetes   kubernetes-admin 

(7)kubectl config delete-context:刪除一個context

root@VM-16-6-ubuntu:~# kubectl config delete-context admin1@k8s1
deleted context admin1@k8s1 from /etc/kubernetes/admin.conf
root@VM-16-6-ubuntu:~# kubectl config get-contexts
CURRENT   NAME                          CLUSTER      AUTHINFO           NAMESPACE
*         kubernetes-admin@kubernetes   kubernetes   kubernetes-admin 

(8)kubectl config current-context:查看當前所使用的context

root@VM-16-6-ubuntu:~# kubectl config current-context
kubernetes-admin@kubernetes

(9)kubectl config use-context:切換context

root@VM-16-6-ubuntu:~# kubectl config set-context admin1@k8s1 --user=admin1
Context "admin1@k8s1" created.
root@VM-16-6-ubuntu:~# kubectl config use-context admin1@k8s1
Switched to context "admin1@k8s1".
root@VM-16-6-ubuntu:~# kubectl config current-context
admin1@k8s1

(10)kubectl config set-credentials:添加一個用戶

root@VM-16-6-ubuntu:~# kubectl config set-credentials admin1 --username=admin1 --password=abcd
User "admin1" set.

在kubeconfig中可以看到如下信息:

users:
- name: admin1
  user:
    password: abcd
    username: admin1

 

2.集群控制:kubectl create/apply/delete/label/edit/expose/scale

(1)kubectl create:創建pod

編寫配置文件:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: deployment-example
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.10

集群創建以及查看:

root@VM-16-6-ubuntu:~/test# kubectl create -f nginx-deployment.yaml 
deployment.apps "deployment-example" created
root@VM-16-6-ubuntu:~/test# kubectl get pods
NAME                                 READY     STATUS              RESTARTS   AGE
deployment-example-9956dd665-prkn9   0/1       ContainerCreating   0          44s
deployment-example-9956dd665-wwbvr   0/1       ContainerCreating   0          44s
root@VM-16-6-ubuntu:~/test# kubectl get pods
NAME                                 READY     STATUS    RESTARTS   AGE
deployment-example-9956dd665-prkn9   1/1       Running   0          4m
deployment-example-9956dd665-wwbvr   1/1       Running   0          4m
#顯示標簽信息:
root@VM-16-6-ubuntu:~/test# kubectl get pods --show-labels
NAME                                 READY     STATUS    RESTARTS   AGE       LABELS
deployment-example-9956dd665-prkn9   1/1       Running   0          13m       app=nginx,pod-template-hash=551288221
deployment-example-9956dd665-wwbvr   1/1       Running   0          13m       app=nginx,pod-template-hash=551288221

(2)給pod打標簽

root@VM-16-6-ubuntu:~/test# kubectl label pods/deployment-example-9956dd665-wwbvr status=healthy
pod "deployment-example-9956dd665-wwbvr" labeled
root@VM-16-6-ubuntu:~/test# kubectl get pods --show-labels
NAME                                 READY     STATUS    RESTARTS   AGE       LABELS
deployment-example-9956dd665-prkn9   1/1       Running   0          14m       app=nginx,pod-template-hash=551288221
deployment-example-9956dd665-wwbvr   1/1       Running   0          14m       app=nginx,pod-template-hash=551288221,status=healthy

(3)編輯pod的配置文件

root@VM-16-6-ubuntu:~/test# kubectl edit deployment/deployment-example
deployment.extensions "deployment-example" edited

這個文件屬於臨時文件,現在將pod中的容器數量replicas變更為4。
查看pods信息:

root@VM-16-6-ubuntu:~/test# kubectl get pods --show-labels
NAME                                 READY     STATUS    RESTARTS   AGE       LABELS
deployment-example-9956dd665-jpbvw   1/1       Running   0          10s       app=nginx,pod-template-hash=551288221
deployment-example-9956dd665-pmng2   1/1       Running   0          10s       app=nginx,pod-template-hash=551288221
deployment-example-9956dd665-prkn9   1/1       Running   0          17m       app=nginx,pod-template-hash=551288221
deployment-example-9956dd665-wwbvr   1/1       Running   0          17m       app=nginx,pod-template-hash=551288221,status=healthy

(4)使用kubectl scale也可以操作pod的yaml文件配置

直接修改配置文件的內容,而不需要打開文件。

root@VM-16-6-ubuntu:~/test# kubectl scale --replicas=10 deployment/deployment-example
deployment.extensions "deployment-example" scaled
root@VM-16-6-ubuntu:~/test# kubectl get pods --show-labels
NAME                                 READY     STATUS    RESTARTS   AGE       LABELS
deployment-example-9956dd665-246zt   1/1       Running   0          8s        app=nginx,pod-template-hash=551288221
deployment-example-9956dd665-424r4   1/1       Running   0          8s        app=nginx,pod-template-hash=551288221
deployment-example-9956dd665-jpbvw   1/1       Running   0          14m       app=nginx,pod-template-hash=551288221
deployment-example-9956dd665-pdcff   1/1       Running   0          8s        app=nginx,pod-template-hash=551288221
deployment-example-9956dd665-pmng2   1/1       Running   0          14m       app=nginx,pod-template-hash=551288221
deployment-example-9956dd665-prkn9   1/1       Running   0          32m       app=nginx,pod-template-hash=551288221
deployment-example-9956dd665-rwq8t   1/1       Running   0          8s        app=nginx,pod-template-hash=551288221
deployment-example-9956dd665-tnk99   1/1       Running   0          8s        app=nginx,pod-template-hash=551288221
deployment-example-9956dd665-vsbqk   1/1       Running   0          8s        app=nginx,pod-template-hash=551288221
deployment-example-9956dd665-wwbvr   1/1       Running   0          32m       app=nginx,pod-template-hash=551288221,status=healthy

(5)通過kubectl apply恢復原始配置

root@VM-16-6-ubuntu:~/test# kubectl apply -f nginx-deployment.yaml 
Warning: kubectl apply should be used on resource created by either kubectl create --save-config or kubectl apply
deployment.apps "deployment-example" configured
root@VM-16-6-ubuntu:~/test# kubectl get pods --show-labels
NAME                                 READY     STATUS        RESTARTS   AGE       LABELS
deployment-example-9956dd665-246zt   0/1       Terminating   0          3m        app=nginx,pod-template-hash=551288221
deployment-example-9956dd665-424r4   0/1       Terminating   0          3m        app=nginx,pod-template-hash=551288221
deployment-example-9956dd665-jpbvw   0/1       Terminating   0          17m       app=nginx,pod-template-hash=551288221
deployment-example-9956dd665-pdcff   0/1       Terminating   0          3m        app=nginx,pod-template-hash=551288221
deployment-example-9956dd665-pmng2   0/1       Terminating   0          17m       app=nginx,pod-template-hash=551288221
deployment-example-9956dd665-prkn9   1/1       Running       0          35m       app=nginx,pod-template-hash=551288221
deployment-example-9956dd665-rwq8t   1/1       Terminating   0          3m        app=nginx,pod-template-hash=551288221
deployment-example-9956dd665-vsbqk   0/1       Terminating   0          3m        app=nginx,pod-template-hash=551288221
deployment-example-9956dd665-wwbvr   1/1       Running       0          35m       app=nginx,pod-template-hash=551288221,status=healthy
root@VM-16-6-ubuntu:~/test# kubectl get pods --show-labels
NAME                                 READY     STATUS        RESTARTS   AGE       LABELS
deployment-example-9956dd665-246zt   0/1       Terminating   0          3m        app=nginx,pod-template-hash=551288221
deployment-example-9956dd665-jpbvw   0/1       Terminating   0          17m       app=nginx,pod-template-hash=551288221
deployment-example-9956dd665-pdcff   0/1       Terminating   0          3m        app=nginx,pod-template-hash=551288221
deployment-example-9956dd665-prkn9   1/1       Running       0          35m       app=nginx,pod-template-hash=551288221
deployment-example-9956dd665-rwq8t   0/1       Terminating   0          3m        app=nginx,pod-template-hash=551288221
deployment-example-9956dd665-wwbvr   1/1       Running       0          35m       app=nginx,pod-template-hash=551288221,status=healthy
root@VM-16-6-ubuntu:~/test# kubectl get pods --show-labels
NAME                                 READY     STATUS    RESTARTS   AGE       LABELS
deployment-example-9956dd665-prkn9   1/1       Running   0          35m       app=nginx,pod-template-hash=551288221
deployment-example-9956dd665-wwbvr   1/1       Running   0          35m       app=nginx,pod-template-hash=551288221,status=healthy

(6)通過kubectl delete刪除pod

root@VM-16-6-ubuntu:~/test# kubectl delete -f nginx-deployment.yaml 
deployment.apps "deployment-example" deleted
root@VM-16-6-ubuntu:~/test# kubectl get pods --show-labels
NAME                                 READY     STATUS        RESTARTS   AGE       LABELS
deployment-example-9956dd665-prkn9   0/1       Terminating   0          37m       app=nginx,pod-template-hash=551288221
root@VM-16-6-ubuntu:~/test# kubectl get pods --show-labels
No resources found.

 

3.集群查看和問題調試:kubectl get/describe/logs/exec/attach

(1)kubectl get:獲取對象的信息,可以是pod、node等

root@VM-16-6-ubuntu:~/test# kubectl get pods
NAME                                 READY     STATUS    RESTARTS   AGE
deployment-example-9956dd665-2ksc4   1/1       Running   0          10m
deployment-example-9956dd665-rdwwc   1/1       Running   0          10m
root@VM-16-6-ubuntu:~/test# kubectl get nodes
NAME             STATUS    ROLES     AGE       VERSION
vm-0-3-ubuntu    Ready     <none>    2d        v1.10.2
vm-16-6-ubuntu   Ready     master    2d        v1.10.2
vm-16-8-ubuntu   Ready     <none>    2d        v1.10.2

(2)kubeadm descrbe:查看特定資源或資源組的描述信息

root@VM-16-6-ubuntu:~/test# kubectl describe pods/deployment-example-9956dd665-rdwwc
Name:           deployment-example-9956dd665-rdwwc
Namespace:      default
Node:           vm-16-8-ubuntu/172.27.16.8
Start Time:     Fri, 21 Jun 2019 22:32:45 +0800
Labels:         app=nginx
                pod-template-hash=551288221
Annotations:    <none>
Status:         Running
IP:             192.168.20.1
Controlled By:  ReplicaSet/deployment-example-9956dd665
Containers:
  nginx:
    Container ID:   docker://dd4f3ca81bbc5e6dc56f33d3c3bdb1700212e65a6024956e2bf45fc81614ee42
    Image:          nginx:1.10
    Image ID:       docker-pullable://nginx@sha256:6202beb06ea61f44179e02ca965e8e13b961d12640101fca213efbfd145d7575
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Fri, 21 Jun 2019 22:32:46 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-44qwv (ro)
Conditions:
  Type           Status
  Initialized    True 
  Ready          True 
  PodScheduled   True 
Volumes:
  default-token-44qwv:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-44qwv
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type    Reason                 Age   From                     Message
  ----    ------                 ----  ----                     -------
  Normal  Scheduled              50s   default-scheduler        Successfully assigned deployment-example-9956dd665-rdwwc to vm-16-8-ubuntu
  Normal  SuccessfulMountVolume  50s   kubelet, vm-16-8-ubuntu  MountVolume.SetUp succeeded for volume "default-token-44qwv"
  Normal  Pulled                 49s   kubelet, vm-16-8-ubuntu  Container image "nginx:1.10" already present on machine
  Normal  Created                49s   kubelet, vm-16-8-ubuntu  Created container
  Normal  Started                49s   kubelet, vm-16-8-ubuntu  Started container

(3)kubeadm exec在容器內執行命令

root@VM-16-6-ubuntu:~/test# kubectl exec deployment-example-9956dd665-rdwwc -- cat /etc/nginx/nginx.conf 
user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}

(4)kubectl logs查看容器的日志輸出

root@VM-16-6-ubuntu:~/test# kubectl logs pods/deployment-example-9956dd665-rdwwc

使用-f參數可以查看實時日志輸出。

(5)kubectl attach進入到容器內部

root@VM-16-6-ubuntu:~/test# kubectl attach deployment-example-9956dd665-rdwwc

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM