kubernetes快速入門


            kubernetes快速入門

                                     作者:尹正傑

版權聲明:原創作品,謝絕轉載!否則將追究法律責任。

 

 

 

一.API Server客戶端命令工具kubectl使用入門

1>.查看kubectl命令的幫助信息

[root@master200.yinzhengjie.org.cn ~]# kubectl -h
kubectl controls the Kubernetes cluster manager.

 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         Take a replication controller, service, deployment or pod and expose it as a new Kubernetes Service
  run            Run a particular image on the cluster
  set            Set specific features on objects

Basic Commands (Intermediate):
  explain        Documentation of resources
  get            Display one or many resources
  edit           Edit a resource on the server
  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          Set a new size for a Deployment, ReplicaSet or Replication Controller
  autoscale      Auto-scale a Deployment, ReplicaSet, or ReplicationController

Cluster Management Commands:
  certificate    Modify certificate resources.
  cluster-info   Display cluster info
  top            Display Resource (CPU/Memory/Storage) usage.
  cordon         Mark node as unschedulable
  uncordon       Mark node as schedulable
  drain          Drain node in preparation for maintenance
  taint          Update the taints on one or more nodes

Troubleshooting and Debugging Commands:
  describe       Show details of a specific resource or group of resources
  logs           Print the logs for a container in a pod
  attach         Attach to a running container
  exec           Execute a command in a container
  port-forward   Forward one or more local ports to a pod
  proxy          Run a proxy to the Kubernetes API server
  cp             Copy files and directories to and from containers.
  auth           Inspect authorization

Advanced Commands:
  diff           Diff live version against would-be applied version
  apply          Apply a configuration to a resource by filename or stdin
  patch          Update field(s) of a resource using strategic merge patch
  replace        Replace a resource by filename or stdin
  wait           Experimental: Wait for a specific condition on one or many resources.
  convert        Convert config files between different API versions
  kustomize      Build a kustomization target from a directory or a remote url.

Settings Commands:
  label          Update the labels on a resource
  annotate       Update the annotations on a resource
  completion     Output shell completion code for the specified shell (bash or zsh)

Other Commands:
  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         Modify kubeconfig files
  plugin         Provides utilities for interacting with plugins.
  version        Print the client and server version information

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).
[root@master200.yinzhengjie.org.cn ~]# 

2>.查看k8s node信息(需要注意的是,node是集群級別的資源)

[root@master200.yinzhengjie.org.cn ~]# kubectl get node
NAME                           STATUS   ROLES    AGE   VERSION
master200.yinzhengjie.org.cn   Ready    master   9h    v1.17.2
node201.yinzhengjie.org.cn     Ready    <none>   9h    v1.17.2
node202.yinzhengjie.org.cn     Ready    <none>   8h    v1.17.2
node203.yinzhengjie.org.cn     Ready    <none>   8h    v1.17.2
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get node

3>.查看k8s 集群的名稱空間

[root@master200.yinzhengjie.org.cn ~]# kubectl get ns              #查看所有的名稱空間
NAME              STATUS   AGE
default           Active   9h
kube-node-lease   Active   9h
kube-public       Active   9h
kube-system       Active   9h
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get ns default          #查看指定的名稱空間
NAME      STATUS   AGE
default   Active   9h
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get ns kube-node-lease
NAME              STATUS   AGE
kube-node-lease   Active   9h
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get ns kube-public
NAME          STATUS   AGE
kube-public   Active   9h
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get ns kube-system
NAME          STATUS   AGE
kube-system   Active   9h
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get namespace kube-system -o yaml        #只查看kube-system的名稱空間信息並以yaml格式顯式 
apiVersion: v1
kind: Namespace
metadata:
  creationTimestamp: "2020-02-04T11:39:31Z"
  name: kube-system
  resourceVersion: "4"
  selfLink: /api/v1/namespaces/kube-system
  uid: bd3792cd-09e4-4ca8-848f-73ac8ea2748c
spec:
  finalizers:
  - kubernetes
status:
  phase: Active
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get ns/kube-system -o yaml             #是上面的簡寫形式
apiVersion: v1
kind: Namespace
metadata:
  creationTimestamp: "2020-02-04T11:39:31Z"
  name: kube-system
  resourceVersion: "4"
  selfLink: /api/v1/namespaces/kube-system
  uid: bd3792cd-09e4-4ca8-848f-73ac8ea2748c
spec:
  finalizers:
  - kubernetes
status:
  phase: Active
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get namespace kube-system -o yaml        #只查看kube-system的名稱空間信息並以yaml格式顯式
[root@master200.yinzhengjie.org.cn ~]# kubectl get namespace kube-system -o json         #只查看kube-system的名稱空間信息並以json格式顯式
{
    "apiVersion": "v1",
    "kind": "Namespace",
    "metadata": {
        "creationTimestamp": "2020-02-04T11:39:31Z",
        "name": "kube-system",
        "resourceVersion": "4",
        "selfLink": "/api/v1/namespaces/kube-system",
        "uid": "bd3792cd-09e4-4ca8-848f-73ac8ea2748c"
    },
    "spec": {
        "finalizers": [
            "kubernetes"
        ]
    },
    "status": {
        "phase": "Active"
    }
}
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get ns/kube-system -o json                #很顯然,是上面的一種簡寫格式
{
    "apiVersion": "v1",
    "kind": "Namespace",
    "metadata": {
        "creationTimestamp": "2020-02-04T11:39:31Z",
        "name": "kube-system",
        "resourceVersion": "4",
        "selfLink": "/api/v1/namespaces/kube-system",
        "uid": "bd3792cd-09e4-4ca8-848f-73ac8ea2748c"
    },
    "spec": {
        "finalizers": [
            "kubernetes"
        ]
    },
    "status": {
        "phase": "Active"
    }
}
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get namespace kube-system -o json         #只查看kube-system的名稱空間信息並以json格式顯式

4>.查看指定名稱空間的pod(在k8s中容器被封裝成pod)

[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n kube-system 
NAME                                                   READY   STATUS    RESTARTS   AGE
coredns-6955765f44-455fh                               1/1     Running   1          9h
coredns-6955765f44-q6zqj                               1/1     Running   1          9h
etcd-master200.yinzhengjie.org.cn                      1/1     Running   1          9h
kube-apiserver-master200.yinzhengjie.org.cn            1/1     Running   1          9h
kube-controller-manager-master200.yinzhengjie.org.cn   1/1     Running   1          9h
kube-flannel-ds-amd64-hnnhb                            1/1     Running   1          9h
kube-flannel-ds-amd64-jhmh6                            1/1     Running   1          8h
kube-flannel-ds-amd64-lnldz                            1/1     Running   2          9h
kube-flannel-ds-amd64-nwv2l                            1/1     Running   1          8h
kube-proxy-2shb4                                       1/1     Running   1          9h
kube-proxy-6r9dx                                       1/1     Running   1          9h
kube-proxy-cg2m6                                       1/1     Running   1          8h
kube-proxy-lp5pr                                       1/1     Running   1          8h
kube-scheduler-master200.yinzhengjie.org.cn            1/1     Running   1          9h
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n kube-system
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n kube-system -o wide
NAME                                                   READY   STATUS    RESTARTS   AGE   IP              NODE                           NOMINATED NODE   READINESS GATES
coredns-6955765f44-455fh                               1/1     Running   1          9h    10.244.0.5      master200.yinzhengjie.org.cn   <none>           <none>
coredns-6955765f44-q6zqj                               1/1     Running   1          9h    10.244.0.4      master200.yinzhengjie.org.cn   <none>           <none>
etcd-master200.yinzhengjie.org.cn                      1/1     Running   1          9h    172.200.1.200   master200.yinzhengjie.org.cn   <none>           <none>
kube-apiserver-master200.yinzhengjie.org.cn            1/1     Running   1          9h    172.200.1.200   master200.yinzhengjie.org.cn   <none>           <none>
kube-controller-manager-master200.yinzhengjie.org.cn   1/1     Running   1          9h    172.200.1.200   master200.yinzhengjie.org.cn   <none>           <none>
kube-flannel-ds-amd64-hnnhb                            1/1     Running   1          9h    172.200.1.200   master200.yinzhengjie.org.cn   <none>           <none>
kube-flannel-ds-amd64-jhmh6                            1/1     Running   1          8h    172.200.1.203   node203.yinzhengjie.org.cn     <none>           <none>
kube-flannel-ds-amd64-lnldz                            1/1     Running   2          9h    172.200.1.201   node201.yinzhengjie.org.cn     <none>           <none>
kube-flannel-ds-amd64-nwv2l                            1/1     Running   1          8h    172.200.1.202   node202.yinzhengjie.org.cn     <none>           <none>
kube-proxy-2shb4                                       1/1     Running   1          9h    172.200.1.201   node201.yinzhengjie.org.cn     <none>           <none>
kube-proxy-6r9dx                                       1/1     Running   1          9h    172.200.1.200   master200.yinzhengjie.org.cn   <none>           <none>
kube-proxy-cg2m6                                       1/1     Running   1          8h    172.200.1.202   node202.yinzhengjie.org.cn     <none>           <none>
kube-proxy-lp5pr                                       1/1     Running   1          8h    172.200.1.203   node203.yinzhengjie.org.cn     <none>           <none>
kube-scheduler-master200.yinzhengjie.org.cn            1/1     Running   1          9h    172.200.1.200   master200.yinzhengjie.org.cn   <none>           <none>
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n kube-system -o wide          #以長格式顯式pod信息,較比上面的命令內容更加詳細

5>.查看當前系統上支持的資源類型

[root@master200.yinzhengjie.org.cn ~]# kubectl api-resources          #注意哈,NAME那一列是資源的名稱,但是由於有些資源名稱太長了,也有簡寫形式,即"SHORTNAMES"那一列,我在接下來會頻繁使用簡寫形式的資源類型
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
endpointslices                                 discovery.k8s.io               true         EndpointSlice
events                            ev           events.k8s.io                  true         Event
ingresses                         ing          extensions                     true         Ingress
ingresses                         ing          networking.k8s.io              true         Ingress
networkpolicies                   netpol       networking.k8s.io              true         NetworkPolicy
runtimeclasses                                 node.k8s.io                    false        RuntimeClass
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
csidrivers                                     storage.k8s.io                 false        CSIDriver
csinodes                                       storage.k8s.io                 false        CSINode
storageclasses                    sc           storage.k8s.io                 false        StorageClass
volumeattachments                              storage.k8s.io                 false        VolumeAttachment
[root@master200.yinzhengjie.org.cn ~]# 

6>.查看當前集群的deployments控制器

[root@master200.yinzhengjie.org.cn ~]# kubectl get deploy -n kube-system -o wide
NAME      READY   UP-TO-DATE   AVAILABLE   AGE   CONTAINERS   IMAGES                     SELECTOR
coredns   2/2     2            2           9h    coredns      k8s.gcr.io/coredns:1.6.5   k8s-app=kube-dns
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# 

7>.創建資源(以創建名稱空間為案例)

[root@master200.yinzhengjie.org.cn ~]# kubectl create --help
Create a resource from a file or from stdin.

 JSON and YAML formats are accepted.

Examples:
  # Create a pod using the data in pod.json.
  kubectl create -f ./pod.json
  
  # Create a pod based on the JSON passed into stdin.
  cat pod.json | kubectl create -f -
  
  # Edit the data in docker-registry.yaml in JSON then create the resource using the edited data.
  kubectl create -f docker-registry.yaml --edit -o json

Available Commands:
  clusterrole         Create a ClusterRole.
  clusterrolebinding  Create a ClusterRoleBinding for a particular ClusterRole
  configmap           Create a configmap from a local file, directory or literal value
  cronjob             Create a cronjob with the specified name.
  deployment          Create a deployment with the specified name.
  job                 Create a job with the specified name.
  namespace           Create a namespace with the specified name
  poddisruptionbudget Create a pod disruption budget with the specified name.
  priorityclass       Create a priorityclass with the specified name.
  quota               Create a quota with the specified name.
  role                Create a role with single rule.
  rolebinding         Create a RoleBinding for a particular Role or ClusterRole
  secret              Create a secret using specified subcommand
  service             Create a service using specified subcommand.
  serviceaccount      Create a service account with the specified name

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.
      --dry-run=false: If true, only print the object that would be sent, without sending it.
      --edit=false: Edit the API resource before creating
  -f, --filename=[]: Filename, directory, or URL to files to use to create the resource
  -k, --kustomize='': Process the kustomization directory. This flag can't be used together with -f or -R.
  -o, --output='': Output format. One of:
json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-file.
      --raw='': Raw URI to POST to the server.  Uses the transport specified by the kubeconfig 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.
      --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.
  -l, --selector='': Selector (label query) to filter on, 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].
      --validate=true: If true, use a schema to validate the input before sending it
      --windows-line-endings=false: Only relevant if --edit=true. Defaults to the line ending native to your platform.

Usage:
  kubectl create -f FILENAME [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).
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl create --help
[root@master200.yinzhengjie.org.cn ~]# kubectl get namespace          #查看名稱空間
NAME              STATUS   AGE
default           Active   9h
kube-node-lease   Active   9h
kube-public       Active   9h
kube-system       Active   9h
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get ns               #也是查看名稱空間,只不過這里是簡寫形式而已
NAME              STATUS   AGE
default           Active   9h
kube-node-lease   Active   9h
kube-public       Active   9h
kube-system       Active   9h
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl create namespace operation    #創建一個叫做"operation"的名稱空間
namespace/operation created
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl create ns development
namespace/development created
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl create ns testing
namespace/testing created
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get ns
NAME              STATUS   AGE
default           Active   9h
development       Active   38s
kube-node-lease   Active   9h
kube-public       Active   9h
kube-system       Active   9h
operation         Active   65s
testing           Active   3s
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# 

8>.刪除資源(以刪除名稱空間為案例)

[root@master200.yinzhengjie.org.cn ~]# kubectl delete --help
Delete resources by filenames, stdin, resources and names, or by resources and label selector.

 JSON and YAML formats are accepted. Only one type of the arguments may be specified: filenames, resources and names, or
resources and label selector.

 Some resources, such as pods, support graceful deletion. These resources define a default period before they are
forcibly terminated (the grace period) but you may override that value with the --grace-period flag, or pass --now to
set a grace-period of 1. Because these resources often represent entities in the cluster, deletion may not be
acknowledged immediately. If the node hosting a pod is down or cannot reach the API server, termination may take
significantly longer than the grace period. To force delete a resource, you must pass a grace period of 0 and specify
the --force flag. Note: only a subset of resources support graceful deletion. In absence of the support, --grace-period
is ignored.

 IMPORTANT: Force deleting pods does not wait for confirmation that the pod's processes have been terminated, which can
leave those processes running until the node detects the deletion and completes graceful deletion. If your processes use
shared storage or talk to a remote API and depend on the name of the pod to identify themselves, force deleting those
pods may result in multiple processes running on different machines using the same identification which may lead to data
corruption or inconsistency. Only force delete pods when you are sure the pod is terminated, or if your application can
tolerate multiple copies of the same pod running at once. Also, if you force delete pods the scheduler may place new
pods on those nodes before the node has released those resources and causing those pods to be evicted immediately.

 Note that the delete command does NOT do resource version checks, so if someone submits an update to a resource right
when you submit a delete, their update will be lost along with the rest of the resource.

Examples:
  # Delete a pod using the type and name specified in pod.json.
  kubectl delete -f ./pod.json
  
  # Delete resources from a directory containing kustomization.yaml - e.g. dir/kustomization.yaml.
  kubectl delete -k dir
  
  # Delete a pod based on the type and name in the JSON passed into stdin.
  cat pod.json | kubectl delete -f -
  
  # Delete pods and services with same names "baz" and "foo"
  kubectl delete pod,service baz foo
  
  # Delete pods and services with label name=myLabel.
  kubectl delete pods,services -l name=myLabel
  
  # Delete a pod with minimal delay
  kubectl delete pod foo --now
  
  # Force delete a pod on a dead node
  kubectl delete pod foo --grace-period=0 --force
  
  # Delete all pods
  kubectl delete pods --all

Options:
      --all=false: Delete all resources, including uninitialized ones, in the namespace of the specified resource types.
  -A, --all-namespaces=false: If present, list the requested object(s) across all namespaces. Namespace in current
context is ignored even if specified with --namespace.
      --cascade=true: If true, cascade the deletion of the resources managed by this resource (e.g. Pods created by a
ReplicationController).  Default true.
      --field-selector='': Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector
key1=value1,key2=value2). The server only supports a limited number of field queries per type.
  -f, --filename=[]: containing the resource to delete.
      --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.
      --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).
      --ignore-not-found=false: Treat "resource not found" as a successful delete. Defaults to "true" when --all is
specified.
  -k, --kustomize='': Process a kustomization directory. This flag can't be used together with -f or -R.
      --now=false: If true, resources are signaled for immediate shutdown (same as --grace-period=1).
  -o, --output='': Output mode. Use "-o name" for shorter output (resource/name).
      --raw='': Raw URI to DELETE to the server.  Uses the transport specified by the kubeconfig file.
  -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.
      --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
      --wait=true: If true, wait for resources to be gone before returning. This waits for finalizers.

Usage:
  kubectl delete ([-f FILENAME] | [-k DIRECTORY] | TYPE [(NAME | -l label | --all)]) [options]

Use "kubectl options" for a list of global command-line options (applies to all commands).
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl delete --help
[root@master200.yinzhengjie.org.cn ~]# kubectl get ns
NAME              STATUS   AGE
default           Active   10h
development       Active   7m14s
kube-node-lease   Active   10h
kube-public       Active   10h
kube-system       Active   10h
operation         Active   7m41s
testing           Active   6m39s
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl delete ns operation      #刪除名稱為"operation"名稱空間,如果想要刪除多個名稱空間使用空格隔開即可(刪除資源時會刪除該名稱空間下的所有pods資源,因此刪除名稱空間是很危險的操作,生產環境要謹慎操作哈~)
namespace "operation" deleted
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl delete ns/development ns/testing    #當然,我們也可以使用這種方式刪除多個名稱空間
namespace "development" deleted
[root@master200.yinzhengjie.org.cn ~]# 
 namespace "testing" deleted
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get namespace
NAME              STATUS   AGE
default           Active   10h
kube-node-lease   Active   10h
kube-public       Active   10h
kube-system       Active   10h
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# 

9>.查看資源的描述信息

[root@master200.yinzhengjie.org.cn ~]# kubectl get ns
NAME              STATUS   AGE
default           Active   10h
kube-node-lease   Active   10h
kube-public       Active   10h
kube-system       Active   10h
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl describe ns/kube-system
Name:         kube-system
Labels:       <none>
Annotations:  <none>
Status:       Active

No resource quota.

No LimitRange resource.
[root@master200.yinzhengjie.org.cn ~]# 

10>.創建service

[root@master200.yinzhengjie.org.cn ~]# kubectl create service  --help
Create a service using specified subcommand.

Aliases:
service, svc

Available Commands:
  clusterip    Create a ClusterIP service.
  externalname Create an ExternalName service.
  loadbalancer Create a LoadBalancer service.
  nodeport     Create a NodePort service.

Usage:
  kubectl create service [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).
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl create service --help
[root@master200.yinzhengjie.org.cn ~]# kubectl create service  clusterip --help
Create a ClusterIP service with the specified name.

Examples:
  # Create a new ClusterIP service named my-cs
  kubectl create service clusterip my-cs --tcp=5678:8080
  
  # Create a new ClusterIP service named my-cs (in headless mode)
  kubectl create service clusterip my-cs --clusterip="None"

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.
      --clusterip='': Assign your own ClusterIP or set to 'None' for a 'headless' service (no loadbalancing).
      --dry-run=false: If true, only print the object that would be sent, without sending it.
      --generator='service-clusterip/v1': The name of the API generator to use.
  -o, --output='': Output format. One of:
json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-file.
      --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.
      --tcp=[]: Port pairs can be specified as '<port>:<targetPort>'.
      --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].
      --validate=true: If true, use a schema to validate the input before sending it

Usage:
  kubectl create service clusterip NAME [--tcp=<port>:<targetPort>] [--dry-run] [options]

Use "kubectl options" for a list of global command-line options (applies to all commands).
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl create service clusterip --help
[root@master200.yinzhengjie.org.cn ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   10.96.0.1    <none>        443/TCP   11h
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl create service clusterip nginx-service --tcp=80:80      #創建一個名稱為"nginx-service"的service資源,指定tcp 80端口映射到目標的80端口,IP地址會動態分配
service/nginx-service created
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get svc
NAME            TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE
kubernetes      ClusterIP   10.96.0.1       <none>        443/TCP   11h
nginx-service   ClusterIP   10.111.57.222   <none>        80/TCP    1s
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# kubectl get service
NAME            TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE
kubernetes      ClusterIP   10.96.0.1       <none>        443/TCP   11h
nginx-service   ClusterIP   10.111.57.222   <none>        80/TCP    2m24s
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get svc
NAME            TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE
kubernetes      ClusterIP   10.96.0.1       <none>        443/TCP   11h
nginx-service   ClusterIP   10.111.57.222   <none>        80/TCP    2m33s
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get service/nginx-service -o yaml          #以yaml格式顯式service服務
apiVersion: v1
kind: Service
metadata:
  creationTimestamp: "2020-02-04T23:23:14Z"
  labels:
    app: nginx-service
  name: nginx-service
  namespace: default
  resourceVersion: "31112"
  selfLink: /api/v1/namespaces/default/services/nginx-service
  uid: 3e32c499-5cdd-4986-bca1-abff14c31ee8
spec:
  clusterIP: 10.111.57.222
  ports:
  - name: 80-80
    port: 80
    protocol: TCP
    targetPort: 80
  selector:
    app: nginx-service
  sessionAffinity: None
  type: ClusterIP
status:
  loadBalancer: {}
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get service/nginx-service -o yaml          #以yaml格式顯式service服務

11>.刪除service

[root@master200.yinzhengjie.org.cn ~]# kubectl delete service --help
Delete resources by filenames, stdin, resources and names, or by resources and label selector.

 JSON and YAML formats are accepted. Only one type of the arguments may be specified: filenames, resources and names, or
resources and label selector.

 Some resources, such as pods, support graceful deletion. These resources define a default period before they are
forcibly terminated (the grace period) but you may override that value with the --grace-period flag, or pass --now to
set a grace-period of 1. Because these resources often represent entities in the cluster, deletion may not be
acknowledged immediately. If the node hosting a pod is down or cannot reach the API server, termination may take
significantly longer than the grace period. To force delete a resource, you must pass a grace period of 0 and specify
the --force flag. Note: only a subset of resources support graceful deletion. In absence of the support, --grace-period
is ignored.

 IMPORTANT: Force deleting pods does not wait for confirmation that the pod's processes have been terminated, which can
leave those processes running until the node detects the deletion and completes graceful deletion. If your processes use
shared storage or talk to a remote API and depend on the name of the pod to identify themselves, force deleting those
pods may result in multiple processes running on different machines using the same identification which may lead to data
corruption or inconsistency. Only force delete pods when you are sure the pod is terminated, or if your application can
tolerate multiple copies of the same pod running at once. Also, if you force delete pods the scheduler may place new
pods on those nodes before the node has released those resources and causing those pods to be evicted immediately.

 Note that the delete command does NOT do resource version checks, so if someone submits an update to a resource right
when you submit a delete, their update will be lost along with the rest of the resource.

Examples:
  # Delete a pod using the type and name specified in pod.json.
  kubectl delete -f ./pod.json
  
  # Delete resources from a directory containing kustomization.yaml - e.g. dir/kustomization.yaml.
  kubectl delete -k dir
  
  # Delete a pod based on the type and name in the JSON passed into stdin.
  cat pod.json | kubectl delete -f -
  
  # Delete pods and services with same names "baz" and "foo"
  kubectl delete pod,service baz foo
  
  # Delete pods and services with label name=myLabel.
  kubectl delete pods,services -l name=myLabel
  
  # Delete a pod with minimal delay
  kubectl delete pod foo --now
  
  # Force delete a pod on a dead node
  kubectl delete pod foo --grace-period=0 --force
  
  # Delete all pods
  kubectl delete pods --all

Options:
      --all=false: Delete all resources, including uninitialized ones, in the namespace of the specified resource types.
  -A, --all-namespaces=false: If present, list the requested object(s) across all namespaces. Namespace in current
context is ignored even if specified with --namespace.
      --cascade=true: If true, cascade the deletion of the resources managed by this resource (e.g. Pods created by a
ReplicationController).  Default true.
      --field-selector='': Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector
key1=value1,key2=value2). The server only supports a limited number of field queries per type.
  -f, --filename=[]: containing the resource to delete.
      --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.
      --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).
      --ignore-not-found=false: Treat "resource not found" as a successful delete. Defaults to "true" when --all is
specified.
  -k, --kustomize='': Process a kustomization directory. This flag can't be used together with -f or -R.
      --now=false: If true, resources are signaled for immediate shutdown (same as --grace-period=1).
  -o, --output='': Output mode. Use "-o name" for shorter output (resource/name).
      --raw='': Raw URI to DELETE to the server.  Uses the transport specified by the kubeconfig file.
  -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.
      --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
      --wait=true: If true, wait for resources to be gone before returning. This waits for finalizers.

Usage:
  kubectl delete ([-f FILENAME] | [-k DIRECTORY] | TYPE [(NAME | -l label | --all)]) [options]

Use "kubectl options" for a list of global command-line options (applies to all commands).
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl delete service --help
[root@master200.yinzhengjie.org.cn ~]# kubectl get service
NAME            TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE
kubernetes      ClusterIP   10.96.0.1       <none>        443/TCP   11h
nginx-service   ClusterIP   10.111.57.222   <none>        80/TCP    7m8s
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl delete service/nginx-service
service "nginx-service" deleted
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   10.96.0.1    <none>        443/TCP   11h
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl delete service/nginx-service

12>.以“組/版本”的形式打印服務器上支持的API版本

[root@master200.yinzhengjie.org.cn ~]# kubectl api-versions
admissionregistration.k8s.io/v1
admissionregistration.k8s.io/v1beta1
apiextensions.k8s.io/v1
apiextensions.k8s.io/v1beta1
apiregistration.k8s.io/v1
apiregistration.k8s.io/v1beta1
apps/v1
authentication.k8s.io/v1
authentication.k8s.io/v1beta1
authorization.k8s.io/v1
authorization.k8s.io/v1beta1
autoscaling/v1
autoscaling/v2beta1
autoscaling/v2beta2
batch/v1
batch/v1beta1
certificates.k8s.io/v1beta1
coordination.k8s.io/v1
coordination.k8s.io/v1beta1
discovery.k8s.io/v1beta1
events.k8s.io/v1beta1
extensions/v1beta1
networking.k8s.io/v1
networking.k8s.io/v1beta1
node.k8s.io/v1beta1
policy/v1beta1
rbac.authorization.k8s.io/v1
rbac.authorization.k8s.io/v1beta1
scheduling.k8s.io/v1
scheduling.k8s.io/v1beta1
storage.k8s.io/v1
storage.k8s.io/v1beta1
v1
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl api-versions

13>.監控(watch)正在運行的pod

[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -w
NAME                       READY   STATUS    RESTARTS   AGE
liveness-exec              1/1     Running   6          9m58s
liveness-http              1/1     Running   0          8s
mynginx-677d85dbd5-t9xfz   1/1     Running   0          4h36m
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -w

 

二.使用kubectl部署一個nginx鏡像案例

1>.創建容器之前查看default名稱空間信息

[root@master200.yinzhengjie.org.cn ~]# kubectl get ns
NAME              STATUS   AGE
default           Active   10h
kube-node-lease   Active   10h
kube-public       Active   10h
kube-system       Active   10h
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get all              #注意,此處我們沒有指定名稱空間,那么就是使用的default這個名稱空間喲~
NAME                 TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
service/kubernetes   ClusterIP   10.96.0.1    <none>        443/TCP   10h
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get all -n default        #查看default名稱空間的所有資源
NAME                 TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
service/kubernetes   ClusterIP   10.96.0.1    <none>        443/TCP   10h
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods               #如果咱們沒有指定名稱空間,默認使用的就是default這個名稱空間喲~
No resources found in default namespace.
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods -n default        #查看default名稱空間的pods信息
No resources found in default namespace.
[root@master200.yinzhengjie.org.cn ~]# 

2>.創建一個nginx的pod

[root@master200.yinzhengjie.org.cn ~]# kubectl create deploy --help
Create a deployment with the specified name.

Aliases:
deployment, deploy

Examples:
  # Create a new deployment named my-dep that runs the busybox image.
  kubectl create deployment my-dep --image=busybox

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.
      --dry-run=false: If true, only print the object that would be sent, without sending it.
      --generator='': The name of the API generator to use.
      --image=[]: Image name to run.
  -o, --output='': Output format. One of:
json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-file.
      --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.
      --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].
      --validate=true: If true, use a schema to validate the input before sending it

Usage:
  kubectl create deployment NAME --image=image [--dry-run] [options]

Use "kubectl options" for a list of global command-line options (applies to all commands).
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl create deploy --help
[root@master200.yinzhengjie.org.cn ~]# kubectl create deploy mynginx --image=nginx:1.14-alpine          #注意,部署應用時名稱不要出現大寫字母(即盡量不要使用駝峰命名法),名稱可以使用"-"或者"."進行分割,指定鏡像為"nginx:1.14-alpine"
deployment.apps/mynginx created
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get all 
NAME                           READY   STATUS    RESTARTS   AGE
pod/mynginx-677d85dbd5-zjt8v   1/1     Running   0          17s

NAME                 TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
service/kubernetes   ClusterIP   10.96.0.1    <none>        443/TCP   10h

NAME                      READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/mynginx   1/1     1            1           17s

NAME                                 DESIRED   CURRENT   READY   AGE
replicaset.apps/mynginx-677d85dbd5   1         1         1       17s
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods
NAME                       READY   STATUS    RESTARTS   AGE
mynginx-677d85dbd5-zjt8v   1/1     Running   0          80s
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get pod -o wide
NAME                       READY   STATUS    RESTARTS   AGE   IP           NODE                         NOMINATED NODE   READINESS GATES
mynginx-677d85dbd5-zjt8v   1/1     Running   0          88s   10.244.3.2   node203.yinzhengjie.org.cn   <none>           <none>
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# 

3>.訪問上一步創建的mynginx pod的IP地址可以獲得nginx的默認頁面

[root@master200.yinzhengjie.org.cn ~]# kubectl get pod -o wide
NAME                       READY   STATUS    RESTARTS   AGE     IP           NODE                         NOMINATED NODE   READINESS GATES
mynginx-677d85dbd5-zjt8v   1/1     Running   0          5m28s   10.244.3.2   node203.yinzhengjie.org.cn   <none>           <none>
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# curl 10.244.3.2
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# curl 10.244.3.2

4>.手動刪除pod后k8s會自動幫咱們去創建一個pod

[root@master200.yinzhengjie.org.cn ~]# kubectl get pod -o wide
NAME                       READY   STATUS    RESTARTS   AGE   IP           NODE                         NOMINATED NODE   READINESS GATES
mynginx-677d85dbd5-zjt8v   1/1     Running   0          12m   10.244.3.2   node203.yinzhengjie.org.cn   <none>           <none>
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl delete pods/mynginx-677d85dbd5-zjt8v
pod "mynginx-677d85dbd5-zjt8v" deleted
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get pod -o wide
NAME                       READY   STATUS    RESTARTS   AGE   IP           NODE                         NOMINATED NODE   READINESS GATES
mynginx-677d85dbd5-l5xw2   1/1     Running   0          22s   10.244.1.2   node201.yinzhengjie.org.cn   <none>           <none>
[root@master200.yinzhengjie.org.cn ~]# 

5>.為pods擴容

[root@master200.yinzhengjie.org.cn ~]# kubectl scale --help
Set a new size for a Deployment, ReplicaSet, Replication Controller, or StatefulSet.

 Scale also allows users to specify one or more preconditions for the scale action.

 If --current-replicas or --resource-version is specified, it is validated before the scale is attempted, and it is
guaranteed that the precondition holds true when the scale is sent to the server.

Examples:
  # Scale a replicaset named 'foo' to 3.
  kubectl scale --replicas=3 rs/foo
  
  # Scale a resource identified by type and name specified in "foo.yaml" to 3.
  kubectl scale --replicas=3 -f foo.yaml
  
  # If the deployment named mysql's current size is 2, scale mysql to 3.
  kubectl scale --current-replicas=2 --replicas=3 deployment/mysql
  
  # Scale multiple replication controllers.
  kubectl scale --replicas=5 rc/foo rc/bar rc/baz
  
  # Scale statefulset named 'web' to 3.
  kubectl scale --replicas=3 statefulset/web

Options:
      --all=false: Select all resources 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.
      --current-replicas=-1: Precondition for current size. Requires that the current size of the resource match this
value in order to scale.
  -f, --filename=[]: Filename, directory, or URL to files identifying the resource to set a new size
  -k, --kustomize='': Process the kustomization directory. This flag can't be used together with -f or -R.
  -o, --output='': Output format. One of:
json|yaml|name|go-template|go-template-file|template|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.
      --replicas=0: The new desired number of replicas. Required.
      --resource-version='': Precondition for resource version. Requires that the current resource version match this
value in order to scale.
  -l, --selector='': Selector (label query) to filter on, 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].
      --timeout=0s: The length of time to wait before giving up on a scale operation, zero means don't wait. Any other
values should contain a corresponding time unit (e.g. 1s, 2m, 3h).

Usage:
  kubectl scale [--resource-version=version] [--current-replicas=count] --replicas=COUNT (-f FILENAME | TYPE NAME)
[options]

Use "kubectl options" for a list of global command-line options (applies to all commands).
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl scale --help
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods
NAME                       READY   STATUS    RESTARTS   AGE
mynginx-677d85dbd5-vk5p5   1/1     Running   0          27m
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl scale --replicas=3 deployment mynginx        #我們將自己創建的mynginx應用的副本設置為3,模擬擴容
deployment.apps/mynginx scaled
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods
NAME                       READY   STATUS    RESTARTS   AGE
mynginx-677d85dbd5-gkdb6   1/1     Running   0          2s
mynginx-677d85dbd5-vb8tt   1/1     Running   0          2s
mynginx-677d85dbd5-vk5p5   1/1     Running   0          28m
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# 

6>.為pods縮容

[root@master200.yinzhengjie.org.cn ~]# kubectl get pods
NAME                       READY   STATUS    RESTARTS   AGE
mynginx-677d85dbd5-gkdb6   1/1     Running   0          4m37s
mynginx-677d85dbd5-vb8tt   1/1     Running   0          4m37s
mynginx-677d85dbd5-vk5p5   1/1     Running   0          32m
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl scale --replicas=2 deployment mynginx          #我們將副本設置為2,模擬縮容
deployment.apps/mynginx scaled
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get pods
NAME                       READY   STATUS    RESTARTS   AGE
mynginx-677d85dbd5-gkdb6   1/1     Running   0          4m46s
mynginx-677d85dbd5-vk5p5   1/1     Running   0          32m
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# 

 

三.使用kubectl創建一個service

1>.查看現有的service

[root@master200.yinzhengjie.org.cn ~]# kubectl get service          #查看現有的service資源
NAME         TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   10.96.0.1    <none>        443/TCP   11h
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get svc             #是上面的簡寫形式
NAME         TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   10.96.0.1    <none>        443/TCP   11h
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# 

2>.創建一個service資源(我們可以使用service的IP去訪問關聯的pod資源,如下圖所示,訪問10.109.254.211:80其實訪問的就是10.244.1.2:80喲~)

[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   10.96.0.1    <none>        443/TCP   11h
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl create service clusterip mynginx --tcp=80:80          #注意,此處我故意創建了一個和上面pod同名的服務,這樣創建后它會自動和上面咱們創建的nginx pod進行關聯
service/mynginx created
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get service
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP   11h
mynginx      ClusterIP   10.109.254.211   <none>        80/TCP    9s
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl create service clusterip mynginx --tcp=80:80          #注意,此處我故意創建了一個和上面pod同名的服務,這樣創建后它會自動和上面咱們創建的nginx pod進行關聯
[root@master200.yinzhengjie.org.cn ~]# kubectl get service/mynginx -o yaml                     #以yaml格式顯式名稱為"mynginx"的service資源信息
apiVersion: v1
kind: Service
metadata:
  creationTimestamp: "2020-02-04T23:33:33Z"
  labels:
    app: mynginx
  name: mynginx
  namespace: default
  resourceVersion: "32669"
  selfLink: /api/v1/namespaces/default/services/mynginx
  uid: 19b9ddeb-a630-4637-a854-5f1750e7aaf0
spec:
  clusterIP: 10.109.254.211
  ports:
  - name: 80-80
    port: 80
    protocol: TCP
    targetPort: 80
  selector:
    app: mynginx
  sessionAffinity: None
  type: ClusterIP
status:
  loadBalancer: {}
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get service/mynginx -o yaml                     #以yaml格式顯式名稱為"mynginx"的service資源信息
[root@master200.yinzhengjie.org.cn ~]# kubectl get pod -o wide
NAME                       READY   STATUS    RESTARTS   AGE   IP           NODE                         NOMINATED NODE   READINESS GATES
mynginx-677d85dbd5-l5xw2   1/1     Running   0          70m   10.244.1.2   node201.yinzhengjie.org.cn   <none>           <none>
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl describe svc/mynginx
Name:              mynginx
Namespace:         default
Labels:            app=mynginx
Annotations:       <none>
Selector:          app=mynginx
Type:              ClusterIP
IP:                10.109.254.211
Port:              80-80  80/TCP
TargetPort:        80/TCP
Endpoints:         10.244.1.2:80
Session Affinity:  None
Events:            <none>
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl describe svc/mynginx                         #查看mynginx的service資源詳細信息

3>.手動刪除pod后k8s會自動幫咱們去創建一個pod,於此同時service也會自動關聯喲

[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get pod -o wide
NAME                       READY   STATUS    RESTARTS   AGE   IP           NODE                         NOMINATED NODE   READINESS GATES
mynginx-677d85dbd5-l5xw2   1/1     Running   0          75m   10.244.1.2   node201.yinzhengjie.org.cn   <none>           <none>
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl describe svc/mynginx
Name:              mynginx
Namespace:         default
Labels:            app=mynginx
Annotations:       <none>
Selector:          app=mynginx
Type:              ClusterIP
IP:                10.109.254.211
Port:              80-80  80/TCP
TargetPort:        80/TCP
Endpoints:         10.244.1.2:80
Session Affinity:  None
Events:            <none>
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl delete pods mynginx-677d85dbd5-l5xw2
pod "mynginx-677d85dbd5-l5xw2" deleted
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get pod -o wide
NAME                       READY   STATUS    RESTARTS   AGE   IP           NODE                         NOMINATED NODE   READINESS GATES
mynginx-677d85dbd5-vk5p5   1/1     Running   0          8s    10.244.2.2   node202.yinzhengjie.org.cn   <none>           <none>
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl describe svc/mynginx
Name:              mynginx
Namespace:         default
Labels:            app=mynginx
Annotations:       <none>
Selector:          app=mynginx
Type:              ClusterIP
IP:                10.109.254.211
Port:              80-80  80/TCP
TargetPort:        80/TCP
Endpoints:         10.244.2.2:80
Session Affinity:  None
Events:            <none>
[root@master200.yinzhengjie.org.cn ~]# 

 

 

四.API Server

  我們知道API Server組件對K8S來說是非常重要的,如下圖所示,你得所有操作必須得經過API Server,有點類似於馮諾依曼體系中的總線角色。

  API Server是中央管理實體,也是唯一與分布式存儲組件etcd直接對話的組件,它有以下特點:
    服務器kubernetes API,工作節點在內部使用集群,kubectl在外部使用集群;
    代理集群組件Kubernetes UI有一個叫做Dashboard組件,提供了很好的Web UI,后續我會分享如何部署的筆記;
    允許操作對象的狀態,例如pod和service;
    保存分布式存儲(etcd)中對象的狀態

  Kubernetes API Server是一個以JSON為主要序列化模式的HTTP API,但是它也支持協議緩沖區(grpc),主要用於集群內部通信。
    我們知道顯式的時候可以以yaml格式顯式,那是因為API Server幫咱們將JSON格式轉換成yaml格式的;
    我們給API Server提交請求可以是yaml格式,只不過API Server會自動將咱們提交的yaml格式的文件轉換成json格式喲;
    除了支持JSON格式外,還支持Google公司自己研發的grpc,grpc是一款分布式高性能RPC框架,據說性能要比http協議的REST(REpresentational State Transfer)ful風格要好,因此httpd2.x(基於TCP的分布式協議)和httpd3.x(基於UDP的分布式協議)大量借鑒grpc的設計風格。

  API Server把它的API接口中的資源分成多個邏輯組合:
    API Group:
      每個組合(通常都是一些相關的類型放在一起)就稱作一個API群組。
    作用在於每個組可以獨立演進(迭代),比如改動某個組的API版本並不會影響到整個API Server,而且每個組還可以多版本共存;

  REST(REpresentational State Transfer)是一種體系結構樣式,是一種用於Web開發的體系結構樣式,也是開發Web服務時通常使用的通信方法。
    使用這種風格設計的系統和站點旨在實現快速性能、可靠性和擴展能力(以增加並輕松支持額外用戶);
    為了實現這些目標,開發人員使用可重用的組件,這些組件可以在系統運行時進行管理和更新,而不會影響整個系統;
    RESTful范式規范語法:
      protocol://host(domain name):port/application context/version/resource/parameter
    舉個例子:
      https://haproxy.yinzhengjie.org.cn:8888/status/v1/users/{id}

 

五.資源對象的配置格式

  API Server接收和返回的所有JSON對象都遵循同樣一個模式,它們都具有"kind""apiVersion"字段,用於標識對象所述的資源類型,API群組及相關的版本;
  
  大多數的對象或列表類型的資源還需要具有三個嵌套的字段metadata,spec和status。
    metadata字段:
      為資源提供元數據信息,例如名稱,隸屬的名稱空間和標簽等;
    spec字段:
      用於定義用戶期望的狀態,不同的資源類型,其狀態的意義各不相同,例如pod資源最為核心的功能在於運行容器;
    status字段:
      記錄着活動對象的當前狀態信息,它由Kubernetes系統自行維護,對用戶來說為只讀字段;

  我們可以通過"kubectl api-resources"命令獲取集群支持的所有資源類型。
[root@master200.yinzhengjie.org.cn ~]# 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
endpointslices                                 discovery.k8s.io               true         EndpointSlice
events                            ev           events.k8s.io                  true         Event
ingresses                         ing          extensions                     true         Ingress
ingresses                         ing          networking.k8s.io              true         Ingress
networkpolicies                   netpol       networking.k8s.io              true         NetworkPolicy
runtimeclasses                                 node.k8s.io                    false        RuntimeClass
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
csidrivers                                     storage.k8s.io                 false        CSIDriver
csinodes                                       storage.k8s.io                 false        CSINode
storageclasses                    sc           storage.k8s.io                 false        StorageClass
volumeattachments                              storage.k8s.io                 false        VolumeAttachment
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl api-resources
[root@master200.yinzhengjie.org.cn ~]# kubectl get deploy mynginx -o yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "1"
  creationTimestamp: "2020-02-04T22:14:32Z"
  generation: 3
  labels:
    app: mynginx
  name: mynginx
  namespace: default
  resourceVersion: "39216"
  selfLink: /apis/apps/v1/namespaces/default/deployments/mynginx
  uid: 5c796fe6-03c9-40af-8ec6-0457a379e692
spec:
  progressDeadlineSeconds: 600
  replicas: 2
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      app: mynginx
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
    type: RollingUpdate
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: mynginx
    spec:
      containers:
      - image: nginx:1.14-alpine
        imagePullPolicy: IfNotPresent
        name: nginx
        resources: {}
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
      dnsPolicy: ClusterFirst
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      terminationGracePeriodSeconds: 30
status:
  availableReplicas: 2
  conditions:
  - lastTransitionTime: "2020-02-04T22:14:32Z"
    lastUpdateTime: "2020-02-04T22:14:40Z"
    message: ReplicaSet "mynginx-677d85dbd5" has successfully progressed.
    reason: NewReplicaSetAvailable
    status: "True"
    type: Progressing
  - lastTransitionTime: "2020-02-05T00:11:57Z"
    lastUpdateTime: "2020-02-05T00:11:57Z"
    message: Deployment has minimum availability.
    reason: MinimumReplicasAvailable
    status: "True"
    type: Available
  observedGeneration: 3
  readyReplicas: 2
  replicas: 2
  updatedReplicas: 2
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# 
[root@master200.yinzhengjie.org.cn ~]# kubectl get deploy mynginx -o yaml

 

六.和解循環(Reconciliation Loop)

  和解循環的大致工作流程如下:
    1>.客戶端向API Sever提交POST請求以創建對象         (1)通過JSON格式的body提交;
        (2)YAML格式需要實現完成向JSON的轉換;
        (3)對象配置信息保存於etcd中,其定義出的狀態也稱為"期望的狀態(spec)"
    2>.控制器負責將其創建為kubernetes集群上的具體(活動)對象,並確保其當前狀態(status)與用戶定義的期望狀態相同.
        (1)status由控制器自行維護,而spec則由用戶進行提交;
        (2)活動對象在運行過程中因節點故障等原因可能會在某一時刻導致其status不在吻合於spec;
        (3)控制器通過和解循環(Reconciliation Loop)不間斷地監控着相關對象的當前狀態,在對象的當前狀態發生改變時運行合適的操作讓其當前狀態無限接近與期望的狀態。

 


免責聲明!

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



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