kubernetes快速入门

本文涉及的产品
实时计算 Flink 版,5000CU*H 3个月
容器服务 Serverless 版 ACK Serverless,317元额度 多规格
容器服务 Serverless 版 ACK Serverless,952元额度 多规格
简介: 该博客文章提供了一个关于kubernetes快速入门的指南,涵盖了kubectl命令工具的使用、资源对象操作、以及如何通过kubectl与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)不间断地监控着相关对象的当前状态,在对象的当前状态发生改变时运行合适的操作让其当前状态无限接近与期望的状态。
相关实践学习
通过Ingress进行灰度发布
本场景您将运行一个简单的应用,部署一个新的应用用于新的发布,并通过Ingress能力实现灰度发布。
容器应用与集群管理
欢迎来到《容器应用与集群管理》课程,本课程是“云原生容器Clouder认证“系列中的第二阶段。课程将向您介绍与容器集群相关的概念和技术,这些概念和技术可以帮助您了解阿里云容器服务ACK/ACK Serverless的使用。同时,本课程也会向您介绍可以采取的工具、方法和可操作步骤,以帮助您了解如何基于容器服务ACK Serverless构建和管理企业级应用。 学习完本课程后,您将能够: 掌握容器集群、容器编排的基本概念 掌握Kubernetes的基础概念及核心思想 掌握阿里云容器服务ACK/ACK Serverless概念及使用方法 基于容器服务ACK Serverless搭建和管理企业级网站应用
目录
相关文章
|
监控 Kubernetes Perl
Kubernetes版快速入门的实验报告-9
Kubernetes版快速入门的实验报告-9
109 0
Kubernetes版快速入门的实验报告-9
|
Kubernetes 容器
Kubernetes版快速入门的实验报告-6
Kubernetes版快速入门的实验报告-6
144 0
Kubernetes版快速入门的实验报告-6
|
Web App开发 Kubernetes 负载均衡
阿里云容器服务Kubernetes版快速入门 详情笔记
阿里云容器服务Kubernetes版快速入门 详情笔记
阿里云容器服务Kubernetes版快速入门 详情笔记
|
监控 Kubernetes Perl
Kubernetes版快速入门的实验报告-8
Kubernetes版快速入门的实验报告-8
95 0
Kubernetes版快速入门的实验报告-8
|
Prometheus 运维 监控
Kubernetes版快速入门的实验报告-7
Kubernetes版快速入门的实验报告-7
100 0
Kubernetes版快速入门的实验报告-7
|
Kubernetes 负载均衡 容器
Kubernetes版快速入门的实验报告-5
Kubernetes版快速入门的实验报告-5
116 0
Kubernetes版快速入门的实验报告-5
|
Kubernetes 容器
Kubernetes版快速入门的实验报告-4
Kubernetes版快速入门的实验报告-4
98 0
Kubernetes版快速入门的实验报告-4
|
Kubernetes 容器
Kubernetes版快速入门的实验报告-3
Kubernetes版快速入门的实验报告-3
153 0
Kubernetes版快速入门的实验报告-3
|
Web App开发 Kubernetes 数据安全/隐私保护
Kubernetes版快速入门的实验报告-2
Kubernetes版快速入门的实验报告-2
120 0
Kubernetes版快速入门的实验报告-2
|
Prometheus 运维 监控
基础学习之阿里云容器服务Kubernetes版快速入门
基础学习之阿里云容器服务Kubernetes版快速入门-1
313 0