理論+實操:kubectl命令管理


kubectl 管理

kubectl是管理k8s集羣的命令行工具,通過生成的json格式傳遞給APIserver進行創建、查看、管理的操作

一:查看kubectl信息

[root@master1 dashboard]# kubectl --help
kubectl controls the Kubernetes cluster manager. 
#kubectl控制Kubernetes集羣管理器。

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         使用 replication controller, service, deployment 或者 pod 並暴露它作爲一個 新的 Kubernetes Service
  #使用控制器把資源暴露出來,提供對外服務
  run            在集羣中運行一個指定的鏡像
  
  set            爲 objects 設置一個指定的特徵
  #比如set 可以修改版本號
Basic Commands (Intermediate):
  explain        查看資源的文檔
  get            顯示一個或更多 resources
  edit           在服務器上編輯一個資源
  delete         Delete resources by filenames, stdin, resources and names, or by resources and label selector

Deploy Commands:
  rollout        Manage the rollout of a resource
  #回滾
  scale          爲 Deployment, ReplicaSet, Replication Controller 或者 Job 設置一個新的副本數量
  #多個副本
  autoscale      自動調整一個 Deployment, ReplicaSet, 或者 ReplicationController 的副本數量
  #自動彈性伸縮

Cluster Management Commands:
  certificate    修改 certificate 資源.
  cluster-info   顯示集羣信息
  top            Display Resource (CPU/Memory/Storage) usage.
  cordon         標記 node 爲 unschedulable
  uncordon       標記 node 爲 schedulable
  drain          Drain node in preparation for maintenance
  taint          更新一個或者多個 node 上的 taints

Troubleshooting and Debugging Commands:
  describe       顯示一個指定 resource 或者 group 的 resources 詳情
  logs           輸出容器在 pod 中的日誌
  attach         Attach 到一個運行中的 container
  exec           在一個 container 中執行一個命令
  port-forward   Forward one or more local ports to a pod
  proxy          運行一個 proxy 到 Kubernetes API server
  cp             複製 files 和 directories 到 containers 和從容器中複製 files 和 directories.
  auth           Inspect authorization

Advanced Commands:
  apply          通過文件名或標準輸入流(stdin)對資源進行配置
  patch          使用 strategic merge patch 更新一個資源的 field(s)
  replace        通過 filename 或者 stdin替換一個資源
  wait           Experimental: Wait for a specific condition on one or many resources.
  convert        在不同的 API versions 轉換配置文件

Settings Commands:
  label          更新在這個資源上的 labels
  annotate       更新一個資源的註解
  completion     Output shell completion code for the specified shell (bash or zsh)

Other Commands:
  alpha          Commands for features in alpha
  api-resources  Print the supported API resources on the server
  api-versions   Print the supported API versions on the server, in the form of "group/version"
  config         修改 kubeconfig 文件
  plugin         Provides utilities for interacting with plugins.
  version        輸出 client 和 server 的版本信息

Usage:
  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 run

Usage:
  kubectl run NAME --image=image [--env="key=value"] [--port=port] [--replicas=replicas] [--dry-run=bool]
[--overrides=inline-json] [--command] -- [COMMAND] [args...] [options]
Use "kubectl options" for a list of global command-line options (applies to all commands).
[root@master1 bin]# kubectl run --help
創建並運行一個可能被複制的特定映像。
Creates a deployment or job to manage the created container(s).
#創建部署或作業來管理創建的容器。
例子:
  # 啓動nginx的單個實例。
  kubectl run nginx --image=nginx
  # 啓動hazelcast的單個實例,並讓容器公開端口5701。
  kubectl run hazelcast --image=hazelcast --port=5701
  # 啓動hazelcast的單個實例並設置環境變量“DNS_DOMAIN=cluster”和“POD_NAMESPACE=default”在容器中。
  kubectl run hazelcast --image=hazelcast --env="DNS_DOMAIN=cluster" --env="POD_NAMESPACE=default"
  # 啓動一個hazelcast實例,並在容器中設置標籤“app=hazelcast”和“env=prod”。
  kubectl run hazelcast --image=hazelcast --labels="app=hazelcast,env=prod"
  #啓動nginx的一個複製實例。
  kubectl run nginx --image=nginx --replicas=5
  
  # 乾燥的運行。打印相應的API對象而不創建它們。
  kubectl run nginx --image=nginx --dry-run
  
  # 啓動nginx的單個實例,但是使用從json解析的部分值集合來重載部署規範。
  kubectl run nginx --image=nginx --overrides='{ "apiVersion": "v1", "spec": { ... } }'
  
  # 啓動一組busybox並將其放在前臺,如果它退出,不要重新啓動它。
  kubectl run -i -t busybox --image=busybox --restart=Never
  
  # 使用默認命令啓動nginx容器,但是使用自定義參數(arg1 ..對於那個命令。
  kubectl run nginx --image=nginx -- <arg1> <arg2> ... <argN>
  
  # 使用不同的命令和自定義參數啓動nginx容器。
  kubectl run nginx --image=nginx --command -- <cmd> <arg1> ... <argN>
  
  # 啓動cron作業來計算π- 2000每5分鐘和打印出來的地方。
  kubectl run pi --image=perl --restart=OnFailure -- perl -Mbignum=bpi -wle 'print bpi(2000)'
  
  # 啓動cron作業來計算π- 2000每5分鐘和打印出來的地方。
  kubectl run pi --schedule="0/5 * * * ?" --image=perl --restart=OnFailure -- perl -Mbignum=bpi -wle 'print bpi(2000)'

選項:
      --allow-missing-template-keys=true: If true, ignore any errors in templates when a field or map key is missing in
the template. Only applies to golang and jsonpath output formats.
      --attach=false: If true, wait for the Pod to start running, and then attach to the Pod as if 'kubectl attach ...'
were called.  Default false, unless '-i/--stdin' is set, in which case the default is true. With '--restart=Never' the
exit code of the container process is returned.
      --cascade=true: If true, cascade the deletion of the resources managed by this resource (e.g. Pods created by a
ReplicationController).  Default true.
      --command=false: If true and extra arguments are present, use them as the 'command' field in the container, rather
than the 'args' field which is the default.
      --dry-run=false: If true, only print the object that would be sent, without sending it.
      --env=[]: Environment variables to set in the container
      --expose=false: If true, a public, external service is created for the container(s) which are run
  -f, --filename=[]: to use to replace the resource.
      --force=false: Only used when grace-period=0. If true, immediately remove resources from API and bypass graceful
deletion. Note that immediate deletion of some resources may result in inconsistency or data loss and requires
confirmation.
      --generator='': 使用 API generator 的名字, 在
http://kubernetes.io/docs/user-guide/kubectl-conventions/#generators 查看列表.
      --grace-period=-1: Period of time in seconds given to the resource to terminate gracefully. Ignored if negative.
Set to 1 for immediate shutdown. Can only be set to 0 when --force is true (force deletion).
      --hostport=-1: The host port mapping for the container port. To demonstrate a single-machine container.
      --image='': 指定容器要運行的鏡像.
      --image-pull-policy='': 容器的鏡像拉取策略. 如果爲空, 這個值將不會 被 client 指定且使用
server 端的默認值
  -l, --labels='': Comma separated labels to apply to the pod(s). Will override previous values.
      --leave-stdin-open=false: If the pod is started in interactive mode or with stdin, leave stdin open after the
first attach completes. By default, stdin will be closed after the first attach completes.
      --limits='': The resource requirement limits for this container.  For example, 'cpu=200m,memory=512Mi'.  Note that
server side components may assign limits depending on the server configuration, such as limit ranges.
  -o, --output='': Output format. One of:
json|yaml|name|template|go-template|go-template-file|templatefile|jsonpath|jsonpath-file.
      --overrides='': An inline JSON override for the generated object. If this is non-empty, it is used to override the
generated object. Requires that the object supply a valid apiVersion field.
      --pod-running-timeout=1m0s: The length of time (like 5s, 2m, or 3h, higher than zero) to wait until at least one
pod is running
      --port='': The port that this container exposes.  If --expose is true, this is also the port used by the service
that is created.
      --quiet=false: If true, suppress prompt messages.
      --record=false: Record current kubectl command in the resource annotation. If set to false, do not record the
command. If set to true, record the command. If not set, default to updating the existing annotation value only if one
already exists.
  -R, --recursive=false: Process the directory used in -f, --filename recursively. Useful when you want to manage
related manifests organized within the same directory.
  -r, --replicas=1: Number of replicas to create for this container. Default is 1.
      --requests='': 資源爲 container 請求 requests . 例如, 'cpu=100m,memory=256Mi'.
注意服務端組件也許會賦予 requests, 這決定於服務器端配置, 比如 limit ranges.
      --restart='Always': 這個 Pod 的 restart policy.  Legal values [Always, OnFailure, Never]. 如果設置爲
'Always' 一個 deployment 被創建, 如果設置爲 ’OnFailure' 一個 job 被創建, 如果設置爲 'Never',
一個普通的 pod 被創建. 對於後面兩個 --replicas 必須爲 1.  默認 'Always', 爲 CronJobs 設置爲
`Never`.
      --rm=false: If true, delete resources created in this command for attached containers.
      --save-config=false: If true, the configuration of current object will be saved in its annotation. Otherwise, the
annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future.
      --schedule='': A schedule in the Cron format the job should be run with.
      --service-generator='service/v2': 使用 gnerator 的名稱創建一個 service.  只有在 --expose 爲 true
的時候使用
      --service-overrides='': An inline JSON override for the generated service object. If this is non-empty, it is used
to override the generated object. Requires that the object supply a valid apiVersion field.  Only used if --expose is
true.
      --serviceaccount='': Service account to set in the pod spec
  -i, --stdin=false: Keep stdin open on the container(s) in the pod, even if nothing is attached.
      --template='': Template string or path to template file to use when -o=go-template, -o=go-template-file. The
template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
      --timeout=0s: The length of time to wait before giving up on a delete, zero means determine a timeout from the
size of the object
  -t, --tty=false: Allocated a TTY for each container in the pod.
      --wait=false: If true, wait for resources to be gone before returning. This waits for finalizers.

2.1 創建一個nginx,副本集爲3

控制器deployment自動創建

[root@master1 dashboard]# kubectl run nginx-gsy --image=nginx --port=80 --replicas=3
kubectl run --generator=deployment/apps.v1beta1 is DEPRECATED and will be removed in a future version. Use kubectl create instead.
deployment.apps/nginx-gsy created

查看pods

pod一個個創建,再次查看都在運行狀態

[root@master1 dashboard]# kubectl get pods
NAME                         READY   STATUS              RESTARTS   AGE
nginx-dbddb74b8-sx4m6        1/1     Running             0          5d17h
nginx-gsy-668fbbd8f5-7v8kv   1/1     Running             0          44s
nginx-gsy-668fbbd8f5-brwjf   1/1     Running             0          44s
nginx-gsy-668fbbd8f5-zkrh6   0/1     ContainerCreating   0          44s
[root@master1 dashboard]# kubectl get pods
NAME                         READY   STATUS    RESTARTS   AGE
nginx-dbddb74b8-sx4m6        1/1     Running   0          5d17h
nginx-gsy-668fbbd8f5-7v8kv   1/1     Running   0          62s
nginx-gsy-668fbbd8f5-brwjf   1/1     Running   0          62s
nginx-gsy-668fbbd8f5-zkrh6   1/1     Running   0          62s

–replicas=3代表創建三個資源

kubectl get pods -w 動態監控pod信息

查看pod的網絡狀態,發現都創建在144節點

[root@master1 dashboard]# kubectl get pods -o wide
NAME                         READY   STATUS    RESTARTS   AGE     IP            NODE              NOMINATED NODE
nginx-dbddb74b8-sx4m6        1/1     Running   0          5d17h   172.17.42.3   192.168.247.144   <none>
nginx-gsy-668fbbd8f5-7v8kv   1/1     Running   0          2m56s   172.17.42.4   192.168.247.144   <none>
nginx-gsy-668fbbd8f5-brwjf   1/1     Running   0          2m56s   172.17.42.6   192.168.247.144   <none>
nginx-gsy-668fbbd8f5-zkrh6   1/1     Running   0          2m56s   172.17.42.7   192.168.247.144   <none>

查看節點狀態

[root@master1 dashboard]# kubectl get nodes
NAME              STATUS     ROLES    AGE   VERSION
192.168.247.143   NotReady   <none>   8d    v1.12.3
192.168.247.144   Ready      <none>   8d    v1.12.3

2.2解決node節點掉線問題

此時重啓143的kubelet

[root@node01 ~]# systemctl restart kubelet
[root@node01 ~]# systemctl status kubelet
● kubelet.service - Kubernetes Kubelet
   Loaded: loaded (/usr/lib/systemd/system/kubelet.service; enabled; vendor preset: disabled)
   Active: active (running) since Fri 2020-05-08 13:02:00 CST; 20s ago

然後查看master中的請求證書,重新頒發

[root@master1 dashboard]# kubectl get csr
NAME                                                   AGE    REQUESTOR           CONDITION
node-csr-Xy9S6WNkga8w0P36-gJKl_mnm__GAZ8LZ7Gwg1GTXco   127m   kubelet-bootstrap   Pending
[root@master1 dashboard]# kubectl certificate approve node-csr-Xy9S6WNkga8w0P36-gJKl_mnm__GAZ8LZ7Gwg1GTXco
certificatesigningrequest.certificates.k8s.io/node-csr-Xy9S6WNkga8w0P36-gJKl_mnm__GAZ8LZ7Gwg1GTXco approved
[root@master1 dashboard]# kubectl get csr
NAME                                                   AGE    REQUESTOR           CONDITION
node-csr-Xy9S6WNkga8w0P36-gJKl_mnm__GAZ8LZ7Gwg1GTXco   128m   kubelet-bootstrap   Approved,Issued
[root@master1 dashboard]# kubectl get nodes
NAME              STATUS   ROLES    AGE   VERSION
192.168.247.143   Ready    <none>   8d    v1.12.3
192.168.247.144   Ready    <none>   8d    v1.12.3

2.3 刪掉之前創建的pod資源,重新執行

刪除資源,刪的是控制器

[root@master1 dashboard]# kubectl delete deployment/nginx-gsy
deployment.extensions "nginx-gsy" deleted
[root@master1 dashboard]# kubectl get all
NAME                             READY   STATUS        RESTARTS   AGE
pod/nginx-dbddb74b8-sx4m6        1/1     Running       0          5d17h
pod/nginx-gsy-668fbbd8f5-7v8kv   0/1     Terminating   0          14m
pod/nginx-gsy-668fbbd8f5-brwjf   0/1     Terminating   0          14m
pod/nginx-gsy-668fbbd8f5-zkrh6   0/1     Terminating   0          14m

NAME                 TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
service/kubernetes   ClusterIP   10.0.0.1     <none>        443/TCP   8d

NAME                    DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/nginx   1         1         1            1           5d17h

NAME                              DESIRED   CURRENT   READY   AGE
replicaset.apps/nginx-dbddb74b8   1         1         1       5d17h
[root@master1 dashboard]# kubectl get pods -w
NAME                    READY   STATUS    RESTARTS   AGE
nginx-dbddb74b8-sx4m6   1/1     Running   0          5d17h

重新創建

[root@master1 dashboard]# kubectl run nginx-gsy --image=nginx --port=80 --replicas=3
kubectl run --generator=deployment/apps.v1beta1 is DEPRECATED and will be removed in a future version. Use kubectl create instead.
deployment.apps/nginx-gsy created
[root@master1 dashboard]# kubectl get pods -w
NAME                         READY   STATUS              RESTARTS   AGE
nginx-dbddb74b8-sx4m6        1/1     Running             0          5d17h
nginx-gsy-668fbbd8f5-ch66w   0/1     ContainerCreating   0          3s
nginx-gsy-668fbbd8f5-mmcd4   0/1     ContainerCreating   0          3s
nginx-gsy-668fbbd8f5-q72rw   0/1     ContainerCreating   0          3s
nginx-gsy-668fbbd8f5-mmcd4   1/1   Running   0     5s
nginx-gsy-668fbbd8f5-q72rw   1/1   Running   0     15s
nginx-gsy-668fbbd8f5-ch66w   1/1   Running   0     16s
^C[root@master1 dashboard]# 

此時再查看網絡狀態

加上原有的一個pod資源,四個pod被分攤到各個節點

^C[root@master1 dashboard]# kubectl get pods -o wide
NAME                         READY   STATUS    RESTARTS   AGE     IP            NODE              NOMINATED NODE
nginx-dbddb74b8-sx4m6        1/1     Running   0          5d17h   172.17.42.3   192.168.247.144   <none>
nginx-gsy-668fbbd8f5-ch66w   1/1     Running   0          61s     172.17.45.3   192.168.247.143   <none>
nginx-gsy-668fbbd8f5-mmcd4   1/1     Running   0          61s     172.17.42.4   192.168.247.144   <none>
nginx-gsy-668fbbd8f5-q72rw   1/1     Running   0          61s     172.17.45.4   192.168.247.143   <none>

查看其他,service,deployment,replicaset

[root@master1 dashboard]# kubectl get all
NAME                             READY   STATUS    RESTARTS   AGE
pod/nginx-dbddb74b8-sx4m6        1/1     Running   0          5d17h
pod/nginx-gsy-668fbbd8f5-ch66w   1/1     Running   0          117s
pod/nginx-gsy-668fbbd8f5-mmcd4   1/1     Running   0          117s
pod/nginx-gsy-668fbbd8f5-q72rw   1/1     Running   0          117s

NAME                 TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
service/kubernetes   ClusterIP   10.0.0.1     <none>        443/TCP   8d

NAME                        DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/nginx       1         1         1            1           5d17h
deployment.apps/nginx-gsy   3         3         3            3           117s

NAME                                   DESIRED   CURRENT   READY   AGE
replicaset.apps/nginx-dbddb74b8        1         1         1       5d17h
replicaset.apps/nginx-gsy-668fbbd8f5   3         3         3       117s

2.4 測試,刪掉剛纔創建的其中一個pod

[root@master1 dashboard]# kubectl delete nginx-gsy-668fbbd8f5-mmcd4
error: resource(s) were provided, but no name, label selector, or --all flag specified
錯誤:提供了資源,但沒有指定名稱、標籤選擇器或——all標誌

在創建資源時,pod創建的同時,控制器deployment和副本集replicaset都會同時創建出來

三:expose發佈nginx,創建service服務

service服務提供負載均衡的功能

Usage:
  kubectl expose (-f FILENAME | TYPE NAME) [--port=port] [--protocol=TCP|UDP|SCTP] [--target-port=number-or-name]
[--name=name] [--external-ip=external-ip-of-service] [--type=type] [options]

Use "kubectl options" for a list of global command-line options (applies to all commands).
[root@master1 bin]# kubectl expose --help
Expose a resource as a new Kubernetes service. 

Looks up a deployment, service, replica set, replication controller or pod by name and uses the selector for that
resource as the selector for a new service on the specified port. A deployment or replica set will be exposed as a
service only if its selector is convertible to a selector that service supports, i.e. when the selector contains only
the matchLabels component. Note that if no port is specified via --port and the exposed resource has multiple ports, all
will be re-used by the new service. Also if no labels are specified, the new service will re-use the labels from the
resource it exposes. 

Possible resources include (case insensitive): 

pod (po), service (svc), replicationcontroller (rc), deployment (deploy), replicaset (rs)

Examples:
  # Create a service for a replicated nginx, which serves on port 80 and connects to the containers on port 8000.
  kubectl expose rc nginx --port=80 --target-port=8000
  
  # Create a service for a replication controller identified by type and name specified in "nginx-controller.yaml",
which serves on port 80 and connects to the containers on port 8000.
  kubectl expose -f nginx-controller.yaml --port=80 --target-port=8000
  
  # Create a service for a pod valid-pod, which serves on port 444 with the name "frontend"
  kubectl expose pod valid-pod --port=444 --name=frontend
  
  # Create a second service based on the above service, exposing the container port 8443 as port 443 with the name
"nginx-https"
  kubectl expose service nginx --port=443 --target-port=8443 --name=nginx-https
  
  # Create a service for a replicated streaming application on port 4100 balancing UDP traffic and named 'video-stream'.
  kubectl expose rc streamer --port=4100 --protocol=udp --name=video-stream
  
  # Create a service for a replicated nginx using replica set, which serves on port 80 and connects to the containers on
port 8000.
  kubectl expose rs nginx --port=80 --target-port=8000
  
  # Create a service for an nginx deployment, which serves on port 80 and connects to the containers on port 8000.
  kubectl expose deployment nginx --port=80 --target-port=8000

Options:
      --allow-missing-template-keys=true: If true, ignore any errors in templates when a field or map key is missing in
the template. Only applies to golang and jsonpath output formats.
      --cluster-ip='': ClusterIP to be assigned to the service. Leave empty to auto-allocate, or set to 'None' to create
a headless service.
      --dry-run=false: If true, only print the object that would be sent, without sending it.
      --external-ip='': Additional external IP address (not managed by Kubernetes) to accept for the service. If this IP
is routed to a node, the service can be accessed by this IP in addition to its generated service IP.
  -f, --filename=[]: Filename, directory, or URL to files identifying the resource to expose a service
      --generator='service/v2': 使用 generator 的名稱. 這裏有 2 個 generators: 'service/v1' 和 'service/v2'.
爲一個不同地方是服務端口在 v1 的情況下叫 'default', 如果在 v2 中沒有指定名稱.
默認的名稱是 'service/v2'.
  -l, --labels='': Labels to apply to the service created by this call.
      --load-balancer-ip='': IP to assign to the LoadBalancer. If empty, an ephemeral IP will be created and used
(cloud-provider specific).
      --name='': 名稱爲最新創建的對象.
  -o, --output='': Output format. One of:
json|yaml|name|templatefile|template|go-template|go-template-file|jsonpath|jsonpath-file.
      --overrides='': An inline JSON override for the generated object. If this is non-empty, it is used to override the
generated object. Requires that the object supply a valid apiVersion field.
      --port='': 服務的端口應該被指定. 如果沒有指定, 從被創建的資源中複製
      --protocol='': 創建 service 的時候伴隨着一個網絡協議被創建. 默認是 'TCP'.
      --record=false: Record current kubectl command in the resource annotation. If set to false, do not record the
command. If set to true, record the command. If not set, default to updating the existing annotation value only if one
already exists.
  -R, --recursive=false: Process the directory used in -f, --filename recursively. Useful when you want to manage
related manifests organized within the same directory.
      --save-config=false: If true, the configuration of current object will be saved in its annotation. Otherwise, the
annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future.
      --selector='': A label selector to use for this service. Only equality-based selector requirements are supported.
If empty (the default) infer the selector from the replication controller or replica set.)
      --session-affinity='': If non-empty, set the session affinity for the service to this; legal values: 'None',
'ClientIP'
      --target-port='': Name or number for the port on the container that the service should direct traffic to.
Optional.
      --template='': Template string or path to template file to use when -o=go-template, -o=go-template-file. The
template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
      --type='': Type for this service: ClusterIP, NodePort, LoadBalancer, or ExternalName. Default is 'ClusterIP'.

3.1 expose發佈

[root@master1 dashboard]# kubectl expose deployment nginx-gsy --port=80 --target-port=80 --name=nginx-gsy-service --type=nodeport
The Service "nginx-gsy-service" is invalid: spec.type: Unsupported value: "nodeport": supported values: "ClusterIP", "ExternalName", "LoadBalancer", "NodePort"
[root@master1 dashboard]# kubectl expose deployment nginx-gsy --port=80 --target-port=80 --name=nginx-gsy-service --type=NodePort
service/nginx-gsy-service exposed
[root@master1 dashboard]# kubectl get service
NAME                TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)        AGE
kubernetes          ClusterIP   10.0.0.1     <none>        443/TCP        8d
nginx-gsy-service   NodePort    10.0.0.204   <none>        80:49003/TCP   38s

3.2 在查看資源時,可以將資源名稱簡寫

簡寫格式如下

[root@master1 bin]# kubectl api-resources
NAME                              SHORTNAMES   APIGROUP                       NAMESPACED   KIND
bindings                                                                      true         Binding
componentstatuses                 cs                                          false        ComponentStatus
configmaps                        cm                                          true         ConfigMap
endpoints                         ep                                          true         Endpoints
events                            ev                                          true         Event
limitranges                       limits                                      true         LimitRange
namespaces                        ns                                          false        Namespace
nodes                             no                                          false        Node
persistentvolumeclaims            pvc                                         true         PersistentVolumeClaim
persistentvolumes                 pv                                          false        PersistentVolume
pods                              po                                          true         Pod
podtemplates                                                                  true         PodTemplate
replicationcontrollers            rc                                          true         ReplicationController
resourcequotas                    quota                                       true         ResourceQuota
secrets                                                                       true         Secret
serviceaccounts                   sa                                          true         ServiceAccount
services                          svc                                         true         Service
mutatingwebhookconfigurations                  admissionregistration.k8s.io   false        MutatingWebhookConfiguration
validatingwebhookconfigurations                admissionregistration.k8s.io   false        ValidatingWebhookConfiguration
customresourcedefinitions         crd,crds     apiextensions.k8s.io           false        CustomResourceDefinition
apiservices                                    apiregistration.k8s.io         false        APIService
controllerrevisions                            apps                           true         ControllerRevision
daemonsets                        ds           apps                           true         DaemonSet
deployments                       deploy       apps                           true         Deployment
replicasets                       rs           apps                           true         ReplicaSet
statefulsets                      sts          apps                           true         StatefulSet
tokenreviews                                   authentication.k8s.io          false        TokenReview
localsubjectaccessreviews                      authorization.k8s.io           true         LocalSubjectAccessReview
selfsubjectaccessreviews                       authorization.k8s.io           false        SelfSubjectAccessReview
selfsubjectrulesreviews                        authorization.k8s.io           false        SelfSubjectRulesReview
subjectaccessreviews                           authorization.k8s.io           false        SubjectAccessReview
horizontalpodautoscalers          hpa          autoscaling                    true         HorizontalPodAutoscaler
cronjobs                          cj           batch                          true         CronJob
jobs                                           batch                          true         Job
certificatesigningrequests        csr          certificates.k8s.io            false        CertificateSigningRequest
leases                                         coordination.k8s.io            true         Lease
events                            ev           events.k8s.io                  true         Event
daemonsets                        ds           extensions                     true         DaemonSet
deployments                       deploy       extensions                     true         Deployment
ingresses                         ing          extensions                     true         Ingress
networkpolicies                   netpol       extensions                     true         NetworkPolicy
podsecuritypolicies               psp          extensions                     false        PodSecurityPolicy
replicasets                       rs           extensions                     true         ReplicaSet
networkpolicies                   netpol       networking.k8s.io              true         NetworkPolicy
poddisruptionbudgets              pdb          policy                         true         PodDisruptionBudget
podsecuritypolicies               psp          policy                         false        PodSecurityPolicy
clusterrolebindings                            rbac.authorization.k8s.io      false        ClusterRoleBinding
clusterroles                                   rbac.authorization.k8s.io      false        ClusterRole
rolebindings                                   rbac.authorization.k8s.io      true         RoleBinding
roles                                          rbac.authorization.k8s.io      true         Role
priorityclasses                   pc           scheduling.k8s.io              false        PriorityClass
storageclasses                    sc           storage.k8s.io                 false        StorageClass
volumeattachments                              storage.k8s.io                 false        VolumeAttachment

3.3 查看服務關聯後端的節點

[root@master1 dashboard]# kubectl get endpoints
NAME                ENDPOINTS                                      AGE
kubernetes          192.168.247.148:6443,192.168.247.149:6443      8d
nginx-gsy-service   172.17.42.4:80,172.17.45.3:80,172.17.45.4:80   3m41s

3.4 查看網絡狀態詳細信息

[root@master1 dashboard]# kubectl get all -o wide
NAME                             READY   STATUS    RESTARTS   AGE     IP            NODE              NOMINATED NODE
pod/nginx-dbddb74b8-sx4m6        1/1     Running   0          5d17h   172.17.42.3   192.168.247.144   <none>
pod/nginx-gsy-668fbbd8f5-ch66w   1/1     Running   0          12m     172.17.45.3   192.168.247.143   <none>
pod/nginx-gsy-668fbbd8f5-mmcd4   1/1     Running   0          12m     172.17.42.4   192.168.247.144   <none>
pod/nginx-gsy-668fbbd8f5-q72rw   1/1     Running   0          12m     172.17.45.4   192.168.247.143   <none>

NAME                        TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)        AGE   SELECTOR
service/kubernetes          ClusterIP   10.0.0.1     <none>        443/TCP        8d    <none>
service/nginx-gsy-service   NodePort    10.0.0.204   <none>        80:49003/TCP   64s   run=nginx-gsy

NAME                        DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE     CONTAINERS   IMAGES   SELECTOR
deployment.apps/nginx       1         1         1            1           5d17h   nginx        nginx    run=nginx
deployment.apps/nginx-gsy   3         3         3            3           12m     nginx-gsy    nginx    run=nginx-gsy

NAME                                   DESIRED   CURRENT   READY   AGE     CONTAINERS   IMAGES   SELECTOR
replicaset.apps/nginx-dbddb74b8        1         1         1       5d17h   nginx        nginx    pod-template-hash=dbddb74b8,run=nginx
replicaset.apps/nginx-gsy-668fbbd8f5   3         3         3       12m     nginx-gsy    nginx    pod-template-hash=668fbbd8f5,run=nginx-gsy

3.5 service將node節點的49003負載均衡,可以到node節點上查看

k8s例kube-proxy支持三種模式,在1.8之前我們使用的時iptables以及userspace兩種模式,在kubernetes 1.8之後引入了ipvs模式

[root@node01 ~]# yum install ipvsadm -y 
[root@node01 ~]# ipvsadm -L -n
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
  -> RemoteAddress:Port           Forward Weight ActiveConn InActConn
TCP  192.168.247.143:49003 rr
  -> 172.17.42.4:80               Masq    1      0          0         
  -> 172.17.45.3:80               Masq    1      0          0         
  -> 172.17.45.4:80               Masq    1      0          0                

3.6 在master操作,查看三個pod的訪問日誌

備註:如果訪問其他node便無法訪問檢查proxy組件

訪問一次
在這裏插入圖片描述

[root@master1 dashboard]# kubectl logs nginx-gsy-668fbbd8f5-ch66w
[root@master1 dashboard]# kubectl logs nginx-gsy-668fbbd8f5-mmcd4
[root@master1 dashboard]# kubectl logs nginx-gsy-668fbbd8f5-q72rw
172.17.45.1 - - [08/May/2020:05:34:48 +0000] "GET / HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36" "-"
2020/05/08 05:34:48 [error] 6#6: *1 open() "/usr/share/nginx/html/favicon.ico" failed (2: No such file or directory), client: 172.17.45.1, server: localhost, request: "GET /favicon.ico HTTP/1.1", host: "192.168.247.143:49003", referrer: "http://192.168.247.143:49003/"
172.17.45.1 - - [08/May/2020:05:34:48 +0000] "GET /favicon.ico HTTP/1.1" 404 556 "http://192.168.247.143:49003/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36" "-"

刷新訪問第二次

[root@master1 dashboard]# kubectl logs nginx-gsy-668fbbd8f5-mmcd4
[root@master1 dashboard]# kubectl logs nginx-gsy-668fbbd8f5-ch66w
[root@master1 dashboard]# kubectl logs nginx-gsy-668fbbd8f5-q72rw
172.17.45.1 - - [08/May/2020:05:34:48 +0000] "GET / HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36" "-"
2020/05/08 05:34:48 [error] 6#6: *1 open() "/usr/share/nginx/html/favicon.ico" failed (2: No such file or directory), client: 172.17.45.1, server: localhost, request: "GET /favicon.ico HTTP/1.1", host: "192.168.247.143:49003", referrer: "http://192.168.247.143:49003/"
172.17.45.1 - - [08/May/2020:05:34:48 +0000] "GET /favicon.ico HTTP/1.1" 404 556 "http://192.168.247.143:49003/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36" "-"
172.17.45.1 - - [08/May/2020:05:35:57 +0000] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36" "-"

刷新訪問第三次

[root@master1 dashboard]# kubectl logs nginx-gsy-668fbbd8f5-q72rw
172.17.45.1 - - [08/May/2020:05:34:48 +0000] "GET / HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36" "-"
2020/05/08 05:34:48 [error] 6#6: *1 open() "/usr/share/nginx/html/favicon.ico" failed (2: No such file or directory), client: 172.17.45.1, server: localhost, request: "GET /favicon.ico HTTP/1.1", host: "192.168.247.143:49003", referrer: "http://192.168.247.143:49003/"
172.17.45.1 - - [08/May/2020:05:34:48 +0000] "GET /favicon.ico HTTP/1.1" 404 556 "http://192.168.247.143:49003/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36" "-"
172.17.45.1 - - [08/May/2020:05:35:57 +0000] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36" "-"
172.17.45.1 - - [08/May/2020:05:36:49 +0000] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36" "-"

可能是因爲會話保持,所以三次都訪問同一個pod

清空歷史數據,重新訪問

第一次依舊訪問q72rw

第二次訪問ch66w

[root@master1 dashboard]# kubectl logs nginx-gsy-668fbbd8f5-ch66w
172.17.45.1 - - [08/May/2020:05:40:35 +0000] "GET / HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36" "-"
2020/05/08 05:40:35 [error] 6#6: *3 open() "/usr/share/nginx/html/favicon.ico" failed (2: No such file or directory), client: 172.17.45.1, server: localhost, request: "GET /favicon.ico HTTP/1.1", host: "192.168.247.143:49003", referrer: "http://192.168.247.143:49003/"
172.17.45.1 - - [08/May/2020:05:40:35 +0000] "GET /favicon.ico HTTP/1.1" 404 556 "http://192.168.247.143:49003/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36" "-"

四: 更新nginx版本

更新nginx版本爲1.14

4.1 先查看當前nginx版本

爲1.17.10
在這裏插入圖片描述

4.2 kubectl set 查看信息

[root@master1 bin]# kubectl set --help
Configure application resources 

These commands help you make changes to existing application resources.

Available Commands:
  env            Update environment variables on a pod template
  image          更新一個 pod template 的鏡像
  resources      在對象的 pod templates 上更新資源的 requests/limits
  selector       設置 resource 的 selector
  serviceaccount Update ServiceAccount of a resource
  subject        Update User, Group or ServiceAccount in a RoleBinding/ClusterRoleBinding

Usage:
  kubectl set SUBCOMMAND [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 set image

[root@master1 bin]# kubectl set image --help
更新資源的現有容器映像。

可能的資源包括(不區分大小寫):

  pod (po), replicationcontroller (rc), deployment (deploy), daemonset (ds), replicaset (rs)

Examples:
  # 將部署的nginx容器映像設置爲'nginx:1.9.1',將其busybox容器映像設置爲'busybox'。
  kubectl set image deployment/nginx busybox=busybox nginx=nginx:1.9.1
  
  # 將所有部署'和rc的nginx容器映像更新爲'nginx:1.9.1'
  kubectl set image deployments,rc nginx=nginx:1.9.1 --all
  
  # Update image of all containers of daemonset abc to 'nginx:1.9.1'
  kubectl set image daemonset abc *=nginx:1.9.1
  
  # Print result (in yaml format) of updating nginx container image from local file, without hitting the server
  kubectl set image -f path/to/file.yaml nginx=nginx:1.9.1 --local -o yaml

Options:
      --all=false: Select all resources, including uninitialized ones, in the namespace of the specified resource types
      --allow-missing-template-keys=true: If true, ignore any errors in templates when a field or map key is missing in
the template. Only applies to golang and jsonpath output formats.
      --dry-run=false: If true, only print the object that would be sent, without sending it.
  -f, --filename=[]: Filename, directory, or URL to files identifying the resource to get from a server.
      --include-uninitialized=false: If true, the kubectl command applies to uninitialized objects. If explicitly set to
false, this flag overrides other flags that make the kubectl commands apply to uninitialized objects, e.g., "--all".
Objects with empty metadata.initializers are regarded as initialized.
      --local=false: If true, set image will NOT contact api-server but run locally.
  -o, --output='': Output format. One of:
json|yaml|name|template|go-template|go-template-file|templatefile|jsonpath|jsonpath-file.
      --record=false: Record current kubectl command in the resource annotation. If set to false, do not record the
command. If set to true, record the command. If not set, default to updating the existing annotation value only if one
already exists.
  -R, --recursive=false: Process the directory used in -f, --filename recursively. Useful when you want to manage
related manifests organized within the same directory.
  -l, --selector='': Selector (label query) to filter on, not including uninitialized ones, supports '=', '==', and
'!='.(e.g. -l key1=value1,key2=value2)
      --template='': Template string or path to template file to use when -o=go-template, -o=go-template-file. The
template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].

Usage:
  kubectl set image (-f FILENAME | TYPE NAME) CONTAINER_NAME_1=CONTAINER_IMAGE_1 ... CONTAINER_NAME_N=CONTAINER_IMAGE_N
[options]

Use "kubectl options" for a list of global command-line options (applies to all commands).

4.3 獲取修改模板

kubectl set image deplo/nginx busybox=busybox nginx=nginx:1.9.1

4.4 更新nginx版本

[root@master1 ~]# kubectl set image deployment/nginx-gsy nginx-gsy=nginx:1.14
deployment.extensions/nginx-gsy image updated

4.5 -w實時查看狀態

[root@master1 ~]# kubectl get pods -w
NAME                         READY   STATUS              RESTARTS   AGE
nginx-6c94d899fd-xsxct       1/1     Running             0          3h6m
nginx-gsy-668fbbd8f5-ch66w   1/1     Running             0          3h53m
nginx-gsy-668fbbd8f5-mmcd4   1/1     Running             0          3h53m
nginx-gsy-668fbbd8f5-q72rw   1/1     Running             0          3h53m
nginx-gsy-67ccdc47d9-zbzdh   0/1     ContainerCreating   0          13s
nginx-gsy-67ccdc47d9-zbzdh   1/1   Running   0     21s
nginx-gsy-668fbbd8f5-ch66w   1/1   Terminating   0     3h54m
nginx-gsy-67ccdc47d9-qr9zn   0/1   Pending   0     0s
nginx-gsy-67ccdc47d9-qr9zn   0/1   ContainerCreating   0     0s
nginx-gsy-668fbbd8f5-ch66w   0/1   Terminating   0     3h54m
nginx-gsy-67ccdc47d9-qr9zn   1/1   Running   0     25s
nginx-gsy-668fbbd8f5-q72rw   1/1   Terminating   0     3h54m
nginx-gsy-67ccdc47d9-t8jr7   0/1   Pending   0     0s
nginx-gsy-67ccdc47d9-t8jr7   0/1   ContainerCreating   0     0s
nginx-gsy-668fbbd8f5-q72rw   0/1   Terminating   0     3h54m
nginx-gsy-67ccdc47d9-t8jr7   1/1   Running   0     20s
nginx-gsy-668fbbd8f5-mmcd4   1/1   Terminating   0     3h54m
[root@master1 ~]# 
[root@master1 ~]# kubectl get pods
NAME                         READY   STATUS    RESTARTS   AGE
nginx-6c94d899fd-xsxct       1/1     Running   0          9h
nginx-gsy-67ccdc47d9-qr9zn   1/1     Running   0          6h30m
nginx-gsy-67ccdc47d9-t8jr7   1/1     Running   0          6h30m
nginx-gsy-67ccdc47d9-zbzdh   1/1     Running   0          6h31m

觀察可以發現,更新pod資源的方式是

在原有的三個pod在run的狀態下,首先先創建一個pod,Pending,ContainerCreating,然後Running

接着刪掉原來的一個pod,以此往復,保持副本數量不低於三個,直至所有的pod都被換成新的pod

小結:

資源容器是不可以重啓的,只會被刪除然後重新創建

更新過程中是一個逐步滾動更新狀態

先創建再刪除,始終會保持副本數量,不能低於三個

4.6 查看副本集

[root@master1 ~]# kubectl get replicaset
NAME                   DESIRED   CURRENT   READY   AGE
nginx-6c94d899fd       1         1         1       9h
nginx-dbddb74b8        0         0         0       6d4h
nginx-gsy-668fbbd8f5   0         0         0       10h		#舊的
nginx-gsy-67ccdc47d9   3         3         3       6h36m	#新的

4.7 此時再去訪問nginx

版本變爲1.14

在這裏插入圖片描述

五:回滾nginx

[root@master1 bin]# kubectl rollout --help
Manage the rollout of a resource.
  
Valid resource types include: 

  * deployments  
  * daemonsets  
  * statefulsets

Examples:
  # Rollback to the previous deployment
  kubectl rollout undo deployment/abc
  
  # Check the rollout status of a daemonset
  kubectl rollout status daemonset/foo

Available Commands:
  history     顯示 rollout 歷史
  pause       標記提供的 resource 爲中止狀態
  resume      繼續一個停止的 resource
  status      顯示 rollout 的狀態
  undo        撤銷上一次的 rollout

Usage:
  kubectl rollout SUBCOMMAND [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).

5.1 首先查看一下rollrout歷史

[root@master1 ~]# kubectl rollout history deploy/nginx-gsy
deployment.extensions/nginx-gsy 
REVISION  CHANGE-CAUSE
1         <none>
2         <none>

[root@master1 ~]# 

5.2 執行回滾

[root@master1 ~]# kubectl rollout undo deploy/nginx-gsy
deployment.extensions/nginx-gsy

5.3 實時查看狀態-w

[root@master1 ~]# kubectl get pods -w
NAME                         READY   STATUS              RESTARTS   AGE
nginx-6c94d899fd-xsxct       1/1     Running             0          9h
nginx-gsy-668fbbd8f5-j5psk   0/1     ContainerCreating   0          3s
nginx-gsy-668fbbd8f5-pz7kl   1/1     Running             0          10s
nginx-gsy-67ccdc47d9-qr9zn   1/1     Running             0          6h42m
nginx-gsy-67ccdc47d9-t8jr7   0/1     Terminating         0          6h42m
nginx-gsy-67ccdc47d9-zbzdh   1/1     Running             0          6h42m
nginx-gsy-67ccdc47d9-t8jr7   0/1   Terminating   0     6h42m
nginx-gsy-668fbbd8f5-j5psk   1/1   Running   0     10s
nginx-gsy-67ccdc47d9-qr9zn   1/1   Terminating   0     6h42m
nginx-gsy-668fbbd8f5-cnf72   0/1   Pending   0     0s
nginx-gsy-668fbbd8f5-cnf72   0/1   ContainerCreating   0     0s
nginx-gsy-67ccdc47d9-qr9zn   0/1   Terminating   0     6h42m
nginx-gsy-668fbbd8f5-cnf72   1/1   Running   0     13s
nginx-gsy-67ccdc47d9-zbzdh   1/1   Terminating   0     6h43m
^C[root@master1 ~]# kubect get pods
NAME                         READY   STATUS    RESTARTS   AGE
nginx-6c94d899fd-xsxct       1/1     Running   0          9h
nginx-gsy-668fbbd8f5-cnf72   1/1     Running   0          83s
nginx-gsy-668fbbd8f5-j5psk   1/1     Running   0          93s
nginx-gsy-668fbbd8f5-pz7kl   1/1     Running   0          100s

5.4 查看回滾狀態

[root@master1 ~]# kubectl rollout status deploy/nginx-gsy
deployment "nginx-gsy" successfully rolled out

5.5 再次查看回滾的歷史

狀態雖然回去了,但是序號還是依舊遞增

[root@master1 ~]# kubectl rollout history deploy/nginx-gsy
deployment.extensions/nginx-gsy 
REVISION  CHANGE-CAUSE
2         <none>
3         <none>

5.6 刷新一下網頁

版本變成1.17

在這裏插入圖片描述

六:刪除nginx資源

6.1 刪除控制器deployment

[root@master1 ~]# kubectl get deploy
NAME        DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
nginx       1         1         1            1           6d4h
nginx-gsy   3         3         3            3           10h
[root@master1 ~]# kubectl delete deploy/nginx-gsy
deployment.extensions "nginx-gsy" deleted
[root@master1 ~]# kubectl get deploy
NAME    DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
nginx   1         1         1            1           6d4h
[root@master1 ~]# kubectl get pods
NAME                     READY   STATUS    RESTARTS   AGE
nginx-6c94d899fd-xsxct   1/1     Running   0          9h

6.2 創建pod資源時,還會創建副本集(不指定的話默認爲1)和控制器deployment

這三個都要刪除掉

而且,pod是業務節點,若是將pod對外提供服務的話,還需要進行expose發佈,刪除pod後也要刪除對應的service,以免佔用資源

6.3 刪除服務service

[root@master1 ~]# kubectl get all
NAME                         READY   STATUS    RESTARTS   AGE
pod/nginx-6c94d899fd-xsxct   1/1     Running   0          9h

NAME                        TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)        AGE
service/kubernetes          ClusterIP   10.0.0.1     <none>        443/TCP        8d
service/nginx-gsy-service   NodePort    10.0.0.204   <none>        80:49003/TCP   10h

NAME                    DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/nginx   1         1         1            1           6d4h

NAME                               DESIRED   CURRENT   READY   AGE
replicaset.apps/nginx-6c94d899fd   1         1         1       9h
replicaset.apps/nginx-dbddb74b8    0         0         0       6d4h
[root@master1 ~]# kubectl delete service/nginx-gsy-service
service "nginx-gsy-service" deleted
[root@master1 ~]# kubectl get service
NAME         TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   10.0.0.1     <none>        443/TCP   8d

七:查看資源的具體詳細信息

7.1 查看pod

[root@master1 ~]# kubectl get pods
NAME                     READY   STATUS    RESTARTS   AGE
nginx-6c94d899fd-xsxct   1/1     Running   0          10h
[root@master1 ~]# kubectl describe pod nginx-6c94d899fd-xsxct 
Name:               nginx-6c94d899fd-xsxct
Namespace:          default
Priority:           0
PriorityClassName:  <none>
Node:               192.168.247.144/192.168.247.144
Start Time:         Fri, 08 May 2020 13:57:49 +0800
Labels:             pod-template-hash=6c94d899fd
                    run=nginx
Annotations:        <none>
Status:             Running
IP:                 172.17.42.6
Controlled By:      ReplicaSet/nginx-6c94d899fd
Containers:
  nginx:
    Container ID:   docker://21161e9d900529e8d75d076998600df2fc6a7426d33b3dcc8aad60e21af90cf5
    Image:          nginx:1.14
    Image ID:       docker-pullable://nginx@sha256:f7988fb6c02e0ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Fri, 08 May 2020 13:58:11 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-qm9rm (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  default-token-qm9rm:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-qm9rm
    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:          <none>

7.2 查看deployment

[root@master1 ~]# kubectl describe deploy nginx
Name:                   nginx
Namespace:              default
CreationTimestamp:      Sat, 02 May 2020 19:33:53 +0800
Labels:                 run=nginx
Annotations:            deployment.kubernetes.io/revision: 2
Selector:               run=nginx
Replicas:               1 desired | 1 updated | 1 total | 1 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  25% max unavailable, 25% max surge
Pod Template:
  Labels:  run=nginx
  Containers:
   nginx:
    Image:        nginx:1.14
    Port:         <none>
    Host Port:    <none>
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Conditions:
  Type           Status  Reason
  ----           ------  ------
  Available      True    MinimumReplicasAvailable
  Progressing    True    NewReplicaSetAvailable
OldReplicaSets:  <none>
NewReplicaSet:   nginx-6c94d899fd (1/1 replicas created)
Events:          <none>

7.3 在有些pod的詳細信息中還有一些日誌消息

現在是默認自動調度方法,被調度器所管理

Events:
  Type    Reason     Age   From                      Message
  ----    ------     ----  ----                      -------
  Normal  Scheduled  37s   default-scheduler         Successfully assigned default/nginx-gsy1-7df78bc5fd-bn824 to 192.168.247.143
  Normal  Pulling    36s   kubelet, 192.168.247.143  pulling image "nginx:latest"
  Normal  Pulled     31s   kubelet, 192.168.247.143  Successfully pulled image "nginx:latest"
  Normal  Created    30s   kubelet, 192.168.247.143  Created container
  Normal  Started    30s   kubelet, 192.168.247.143  Started container

7.4 exec 進入pod

[root@master1 ~]# kubectl exec -it nginx-gsy1-7df78bc5fd-bn824 bash
root@nginx-gsy1-7df78bc5fd-bn824:/# ls
bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@nginx-gsy1-7df78bc5fd-bn824:/# ifconfig
bash: ifconfig: command not found
root@nginx-gsy1-7df78bc5fd-bn824:/# yum install net-tools -y
root@nginx-gsy1-7df78bc5fd-bn824:/# yum install net-tools -y
bash: yum: command not found
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章