一、kubectl的命令参数

1)kubectl 能使用的命令。即查看帮助

[root@k8s6 ~]# kubectl 
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         使用 replication controller, service, deployment 或者 pod 并暴露它作为一个 新的
Kubernetes Service
  run            在集群中运行一个指定的镜像
  set            为 objects 设置一个指定的特征

Basic Commands (Intermediate):
  explain        查看资源的文档
  get            显示一个或更多 resources
  edit           在服务器上编辑一个资源
  delete         Delete resources by filenames, stdin, resources and names, or by resources and label selector

Deploy Commands:
  rollout        Manage the rollout of a resource
  scale          为 Deployment, ReplicaSet, Replication Controller 或者 Job 设置一个新的副本数量
  autoscale      自动调整一个 Deployment, ReplicaSet, 或者 ReplicationController 的副本数量

Cluster Management Commands:
  certificate    修改 certificate 资源.
  cluster-info   显示集群信息
  top            Display Resource (CPU/Memory/Storage) usage.
  cordon         标记 node 为 unschedulable
  uncordon       标记 node 为 schedulable
  drain          Drain node in preparation for maintenance
  taint          更新一个或者多个 node 上的 taints

Troubleshooting and Debugging Commands:
  describe       显示一个指定 resource 或者 group 的 resources 详情
  logs           输出容器在 pod 中的日志
  attach         Attach 到一个运行中的 container
  exec           在一个 container 中执行一个命令
  port-forward   Forward one or more local ports to a pod
  proxy          运行一个 proxy 到 Kubernetes API server
  cp             复制 files 和 directories 到 containers 和从容器中复制 files 和 directories.
  auth           Inspect authorization

Advanced Commands:
  diff           Diff live version against would-be applied version
  apply          通过文件名或标准输入流(stdin)对资源进行配置
  patch          使用 strategic merge patch 更新一个资源的 field(s)
  replace        通过 filename 或者 stdin替换一个资源
  wait           Experimental: Wait for a specific condition on one or many resources.
  convert        在不同的 API versions 转换配置文件

Settings Commands:
  label          更新在这个资源上的 labels
  annotate       更新一个资源的注解
  completion     Output shell completion code for the specified shell (bash or zsh)

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

Usage:
  kubectl [flags] [options]

Use "kubectl <command> --help" for more information about a given command.
Use "kubectl options" for a list of global command-line options (applies to all commands).
kubectl

2.1)跑服务命令。kubectl run --help 查看帮助

[root@k8s6 ~]# kubectl run --help
Create and run a particular image, possibly replicated. 

Creates a deployment or job to manage the created container(s).

Examples:
  # Start a single instance of nginx.
  kubectl run nginx --image=nginx
  
  # Start a single instance of hazelcast and let the container expose port 5701 .
  kubectl run hazelcast --image=hazelcast --port=5701
  
  # Start a single instance of hazelcast and set environment variables "DNS_DOMAIN=cluster" and "POD_NAMESPACE=default"
in the container.
  kubectl run hazelcast --image=hazelcast --env="DNS_DOMAIN=cluster" --env="POD_NAMESPACE=default"
  
  # Start a single instance of hazelcast and set labels "app=hazelcast" and "env=prod" in the container.
  kubectl run hazelcast --image=hazelcast --labels="app=hazelcast,env=prod"
  
  # Start a replicated instance of nginx.
  kubectl run nginx --image=nginx --replicas=5
  
  # Dry run. Print the corresponding API objects without creating them.
  kubectl run nginx --image=nginx --dry-run
  
  # Start a single instance of nginx, but overload the spec of the deployment with a partial set of values parsed from
JSON.
  kubectl run nginx --image=nginx --overrides='{ "apiVersion": "v1", "spec": { ... } }'
  
  # Start a pod of busybox and keep it in the foreground, don't restart it if it exits.
  kubectl run -i -t busybox --image=busybox --restart=Never
  
  # Start the nginx container using the default command, but use custom arguments (arg1 .. argN) for that command.
  kubectl run nginx --image=nginx -- <arg1> <arg2> ... <argN>
  
  # Start the nginx container using a different command and custom arguments.
  kubectl run nginx --image=nginx --command -- <cmd> <arg1> ... <argN>
  
  # Start the perl container to compute π to 2000 places and print it out.
  kubectl run pi --image=perl --restart=OnFailure -- perl -Mbignum=bpi -wle 'print bpi(2000)'
  
  # Start the cron job to compute π to 2000 places and print it out every 5 minutes.
  kubectl run pi --schedule="0/5 * * * ?" --image=perl --restart=OnFailure -- perl -Mbignum=bpi -wle 'print bpi(2000)'

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

Usage:
  kubectl run NAME --image=image [--env="key=value"] [--port=port] [--replicas=replicas] [--dry-run=bool]
[--overrides=inline-json] [--command] -- [COMMAND] [args...] [options]

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

2.2)进入交互式的容器服务

[root@k8s6 ~]# kubectl run clinet --image=busybox --replicas=1 -it --restart=Never
If you don't see a command prompt, try pressing enter.
/ # 
/ # 
/ # 
kubectl run clinet --image=busybox --replicas=1 -it --restart=Never

2.3)跑服务,但仅在容器内所在宿主机内可以被访问

运行容器服务
[root@k8s6 ~]# kubectl run nginx-test --image=nginx:1.14-alpine --port=80 --replicas=1
kubectl run --generator=deployment/apps.v1 is DEPRECATED and will be removed in a future version. Use kubectl run --generator=run-pod/v1 or kubectl create instead.
deployment.apps/nginx-test created

查看节点状态
[root@k8s6 ~]# kubectl get pods
NAME                           READY   STATUS              RESTARTS   AGE
nginx-test-5bbfddf46b-g6sh5    0/1     ContainerCreating   0          4s

节点状态Running 起来了,则正常
[root@k8s6 ~]# kubectl get pods
NAME                           READY   STATUS             RESTARTS   AGE
nginx-test-5bbfddf46b-g6sh5    1/1     Running            0          24s

查看节点在那台机器上面
[root@k8s6 ~]# kubectl get pods -o wide
NAME                           READY   STATUS             RESTARTS   AGE   IP           NODE     NOMINATED NODE   READINESS GATES
nginx-test-5bbfddf46b-g6sh5    1/1     Running            0          53s   10.200.2.3   node01   <none>           <none>

此时只能在node01上的机器进行访问
curl 10.200.2.3

删除该服务节点,又重新被创建出来
[root@k8s6 ~]# kubectl delete pods nginx-test-5bbfddf46b-g6sh5
pod "nginx-test-5bbfddf46b-g6sh5" deleted
[root@k8s6 ~]# 
[root@k8s6 ~]# kubectl get pods
NAME                           READY   STATUS              RESTARTS   AGE
nginx-test-5bbfddf46b-6djc4    0/1     ContainerCreating   0          6s
[root@k8s6 ~]# kubectl get pods -o wide
NAME                           READY   STATUS             RESTARTS   AGE   IP           NODE     NOMINATED NODE   READINESS GATES
nginx-test-5bbfddf46b-6djc4    1/1     Running            0          18s   10.200.1.2   node02   <none>           <none>
kubectl run nginx-test --image=nginx:1.14-alpine --port=80 --replicas=1

创建nginx-test 服务,只的镜像名为nginx:1.14-alpine,默认从docker官网下载,容器规模为1

 3)暴露端口,查看帮助

[root@k8s6 ~]# kubectl expose --help
Expose a resource as a new Kubernetes service. 

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

Possible resources include (case insensitive): 

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

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

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

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

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

 3.1)端口暴露给了无法访问的ip

[root@k8s6 ~]# kubectl get deployment
NAME           READY   UP-TO-DATE   AVAILABLE   AGE
nginx-deploy   0/1     1            0           30m
nginx-test     1/1     1            1           17m
[root@k8s6 ~]# kubectl expose deployment nginx-test --name=nginx --port=80 --target-port=80 --protocol=TCP    暴露80端口
service/nginx exposed
[root@k8s6 ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)         AGE
kubernetes   NodePort    10.96.0.1        <none>        443:31234/TCP   38h
nginx        ClusterIP   10.107.169.145   <none>        80/TCP          20s
[root@k8s6 ~]# kubectl get svc -n kube-system        # 查看dns
NAME       TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)         AGE
kube-dns   ClusterIP   10.96.0.10   <none>        53/UDP,53/TCP   38h
[root@k8s6 ~]# kubectl get pods -o wide
NAME                           READY   STATUS             RESTARTS   AGE   IP           NODE     NOMINATED NODE   READINESS GATES
nginx-deploy-79b598b88-2q6vr   0/1     ImagePullBackOff   0          34m   10.200.2.2   node01   <none>           <none>
nginx-test-5bbfddf46b-6djc4    1/1     Running            0          14m   10.200.1.2   node02   <none>           <none>
[root@k8s6 ~]# kubectl describe svc nginx    查看暴露出来的ip
Name:              nginx
Namespace:         default
Labels:            run=nginx-test
Annotations:       <none>
Selector:          run=nginx-test
Type:              ClusterIP
IP:                10.107.169.145
Port:              <unset>  80/TCP
TargetPort:        80/TCP
Endpoints:         10.200.1.2:80
Session Affinity:  None
Events:            <none>
kubectl expose deployment nginx-test --name=nginx --port=80 --target-port=80 --protocol=TCP

4)查看服务的详细信息

[root@k8s6 ~]# kubectl describe deployment nginx-test
Name:                   nginx-test
Namespace:              default
CreationTimestamp:      Wed, 27 Feb 2019 12:56:13 +0800
Labels:                 run=nginx-test
Annotations:            deployment.kubernetes.io/revision: 1
Selector:               run=nginx-test
Replicas:               1 desired | 1 updated | 1 total | 1 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  25% max unavailable, 25% max surge
Pod Template:
  Labels:  run=nginx-test
  Containers:
   nginx-test:
    Image:        nginx:1.14-alpine
    Port:         80/TCP
    Host Port:    0/TCP
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Conditions:
  Type           Status  Reason
  ----           ------  ------
  Progressing    True    NewReplicaSetAvailable
  Available      True    MinimumReplicasAvailable
OldReplicaSets:  <none>
NewReplicaSet:   nginx-test-5bbfddf46b (1/1 replicas created)
Events:
  Type    Reason             Age   From                   Message
  ----    ------             ----  ----                   -------
  Normal  ScalingReplicaSet  34m   deployment-controller  Scaled up replica set nginx-test-5bbfddf46b to 1
kubectl describe deployment nginx-test

5)更改服务的规模

kubectl run nginx-test --image=nginx:1.14-alpine --port=80 --replicas=3        # 创建3个规模的服务
kubectl scale --replicas=5 deployment nginx-test    # 修改规模大小
[root@k8s6 ~]# kubectl get pods
NAME                           READY   STATUS             RESTARTS   AGE
clinet                         1/1     Running            0          12m
nginx-deploy-79b598b88-2q6vr   0/1     ImagePullBackOff   0          54m
nginx-test-5bbfddf46b-6djc4    1/1     Running            0          35m
nginx-test-5bbfddf46b-cwwfm    1/1     Running            0          64s
nginx-test-5bbfddf46b-pcdf2    1/1     Running            0          64s
nginx-test-5bbfddf46b-rpb8r    1/1     Running            0          64s
nginx-test-5bbfddf46b-tttrz    1/1     Running            0          64s
[root@k8s6 ~]# kubectl get pods -o wide
NAME                           READY   STATUS             RESTARTS   AGE   IP           NODE     NOMINATED NODE   READINESS GATES
clinet                         1/1     Running            0          12m   10.200.1.3   node02   <none>           <none>
nginx-test-5bbfddf46b-6djc4    1/1     Running            0          35m   10.200.1.2   node02   <none>           <none>
nginx-test-5bbfddf46b-cwwfm    1/1     Running            0          80s   10.200.1.4   node02   <none>           <none>
nginx-test-5bbfddf46b-pcdf2    1/1     Running            0          80s   10.200.2.6   node01   <none>           <none>
nginx-test-5bbfddf46b-rpb8r    1/1     Running            0          80s   10.200.2.5   node01   <none>           <none>
nginx-test-5bbfddf46b-tttrz    1/1     Running            0          80s   10.200.2.4   node01   <none>           <none>
--replicas=5

6)更换镜像操作

kubectl set image --help  查看帮助

 目标: nginx:1.14-alpine   更换为 nginx:1.15-alpine

6.1)更换前查看使用的镜像

[root@k8s6 ~]# kubectl get pods
NAME                           READY   STATUS             RESTARTS   AGE
clinet                         1/1     Running            0          25m
nginx-deploy-79b598b88-2q6vr   0/1     ImagePullBackOff   0          68m
nginx-test-5bbfddf46b-7cpcq    1/1     Running            0          47s
nginx-test-5bbfddf46b-mbfpq    1/1     Running            0          47s
nginx-test-5bbfddf46b-q28zw    1/1     Running            0          46s
nginx-test-5bbfddf46b-qb66g    1/1     Running            0          46s
nginx-test-5bbfddf46b-xfr8w    1/1     Running            0          47s
[root@k8s6 ~]# kubectl describe pods nginx-test-5bbfddf46b-7cpcq        查看该镜像的详细信息
kubectl describe pods nginx-test-5bbf***

6.2)更换镜像版本操作

kubectl set image deployment nginx-test nginx-test=nginx:1.15-alpine

[root@k8s6 ~]# kubectl set image deployment nginx-test nginx-test=nginx:1.15-alpine
deployment.extensions/nginx-test image updated
[root@k8s6 ~]# kubectl get pods
NAME                           READY   STATUS             RESTARTS   AGE
clinet                         1/1     Running            0          28m
nginx-deploy-79b598b88-2q6vr   0/1     ImagePullBackOff   0          71m
nginx-test-67d85d447c-2phzb    1/1     Running            0          24s
nginx-test-67d85d447c-g7cr2    1/1     Running            0          24s
nginx-test-67d85d447c-j552t    1/1     Running            0          23s
nginx-test-67d85d447c-v7thb    1/1     Running            0          23s
nginx-test-67d85d447c-xx99k    1/1     Running            0          24s
[root@k8s6 ~]# kubectl describe pods nginx-test-67d85d447c-2phzb
Name:               nginx-test-67d85d447c-2phzb
Namespace:          default
Priority:           0
PriorityClassName:  <none>
Node:               node01/192.168.10.23
Start Time:         Wed, 27 Feb 2019 13:54:16 +0800
Labels:             pod-template-hash=67d85d447c
                    run=nginx-test
Annotations:        <none>
Status:             Running
IP:                 10.200.2.12
Controlled By:      ReplicaSet/nginx-test-67d85d447c
Containers:
  nginx-test:
    Container ID:   docker://2e083a772f30777aa86ed8302efed0bb7e2e084cc400886894094ec2c1b3c3ec
    Image:          nginx:1.15-alpine
    Image ID:       docker-pullable://nginx@sha256:e0292d158b6b353fde34909243a4886977cb9d1abb8a8a5fef9e0ff7138dd3e2
    Port:           80/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Wed, 27 Feb 2019 13:54:17 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-r48df (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  default-token-r48df:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-r48df
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  42s   default-scheduler  Successfully assigned default/nginx-test-67d85d447c-2phzb to node01
  Normal  Pulled     41s   kubelet, node01    Container image "nginx:1.15-alpine" already present on machine
  Normal  Created    41s   kubelet, node01    Created container
  Normal  Started    41s   kubelet, node01    Started container
View Code

6.3)回滚镜像

查看回滚帮助

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

  * deployments  
  * daemonsets  
  * statefulsets

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

Available Commands:
  history     显示 rollout 历史
  pause       标记提供的 resource 为中止状态
  resume      继续一个停止的 resource
  status      显示 rollout 的状态
  undo        撤销上一次的 rollout

Usage:
  kubectl rollout SUBCOMMAND [options]

Use "kubectl <command> --help" for more information about a given command.
Use "kubectl options" for a list of global command-line options (applies to all commands).
kubectl rollout --help

kubectl rollout undo deployment nginx-test   默认回滚到上一个版本

 7 ) 编辑服务的 type: ClusterIP  ==》type: NodePort 

[root@k8s6 ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)         AGE
kubernetes   NodePort    10.96.0.1        <none>        443:31234/TCP   38h
nginx        ClusterIP   10.107.169.145   <none>        80/TCP          20s

[root@k8s6 ~]# kubectl edit svc nginx
  type: ClusterIP  ==》type: NodePort   
  
[root@k8s6 ~]# kubectl get svc
NAME         TYPE       CLUSTER-IP       EXTERNAL-IP   PORT(S)         AGE
kubernetes   NodePort   10.96.0.1        <none>        443:31234/TCP   39h
nginx        NodePort   10.107.169.145   <none>        80:31986/TCP    51m

 7.1)此时可通过网页进行访问

http://192.168.10.23:31986/
http://192.168.10.24:31986/

 二、以资源的方式创建资源

1)查看命令行直接创建的资源所描述的yaml文件,资源清单

[root@k8s6 ~]# kubectl get pods
NAME                           READY   STATUS             RESTARTS   AGE
clinet                         1/1     Running            0          26h
nginx-test-67d85d447c-2phzb    1/1     Running            0          25h
nginx-test-67d85d447c-g7cr2    1/1     Running            0          25h
nginx-test-67d85d447c-j552t    1/1     Running            0          25h
nginx-test-67d85d447c-v7thb    1/1     Running            0          25h
nginx-test-67d85d447c-xx99k    1/1     Running            0          25h
[root@k8s6 ~]# kubectl get pod nginx-test-67d85d447c-2phzb -o yaml
kubectl get pod **** -o yaml

2)查看自定义的资源清单需要填写的字段

[root@k8s6 ~]# kubectl explain pods
KIND:     Pod
VERSION:  v1

DESCRIPTION:
     Pod is a collection of containers that can run on a host. This resource is
     created by clients and scheduled onto hosts.

FIELDS:
   apiVersion    <string>
     APIVersion defines the versioned schema of this representation of an
     object. Servers should convert recognized schemas to the latest internal
     value, and may reject unrecognized values. More info:
     https://git.k8s.io/community/contributors/devel/api-conventions.md#resources

   kind    <string>
     Kind is a string value representing the REST resource this object
     represents. Servers may infer this from the endpoint the client submits
     requests to. Cannot be updated. In CamelCase. More info:
     https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds

   metadata    <Object>
     Standard object's metadata. More info:
     https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata

   spec    <Object>
     Specification of the desired behavior of the pod. More info:
     https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status

   status    <Object>
     Most recently observed status of the pod. This data may not be up to date.
     Populated by the system. Read-only. More info:
     https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status
kubectl explain pods

3)定义 yaml 资源清单启动容器

[root@k8s6 ~]# mkdird -p manifests
[root@k8s6 ~]# cd manifests/
[root@k8s6 manifests]# vim pod-demo.yaml
[root@k8s6 manifests]# cat pod-demo.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: pod-demo
  namespace: default
  labels:
    app: myapp
    tier: frontend
spec:
  containers:
  - name: myapp
    image: nginx:1.14-alpine
  - name: busybox
    image: busybox:latest
    command:
    - "/bin/sh"
    - "-c"
    - "echo $(data) >> /usr/share/nginx/html/index.html;sleep 5" 
cat pod-demo.yaml

该清单中使用了2个容器,并且使用了命令操作。该命令使用错误,多容器操作需要恭喜存储卷

4)根据清单启动服务

[root@k8s6 manifests]# kubectl create -f pod-demo.yaml 
pod/pod-demo created
[root@k8s6 manifests]# kubectl get pods -w
NAME                           READY   STATUS             RESTARTS   AGE
clinet                         1/1     Running            0          28h
nginx-test-67d85d447c-2phzb    1/1     Running            0          27h
nginx-test-67d85d447c-g7cr2    1/1     Running            0          27h
nginx-test-67d85d447c-j552t    1/1     Running            0          27h
nginx-test-67d85d447c-v7thb    1/1     Running            0          27h
nginx-test-67d85d447c-xx99k    1/1     Running            0          27h
pod-demo                       1/2     CrashLoopBackOff   3          100s
kubectl create -f pod-demo.yaml

可以看到该服务只启动了好了一个容器

4.1)对启动的容器进行排查。查看日志

[root@k8s6 manifests]# kubectl logs pod-demo myapp
[root@k8s6 manifests]# kubectl logs pod-demo busybox
/bin/sh: data: not found
/bin/sh: can't create /usr/share/nginx/html/index.html: nonexistent directory
kubectl logs pod-demo busybox

5)删除该服务

[root@k8s6 manifests]# kubectl delete pods pod-demo
pod "pod-demo" deleted

 6)修改资源清单,为简单的sleep,再创建,可以看到容器正常跑起来了

[root@k8s6 manifests]# cat pod-demo.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: pod-demo
  namespace: default
  labels:
    app: myapp
    tier: frontend
spec:
  containers:
  - name: myapp
    image: nginx:1.14-alpine
  - name: busybox
    image: busybox:latest
    command:
    - "/bin/sh"
    - "-c"
    - "sleep 3600" 
kubectl create -f pod-demo.yaml
[root@k8s6 manifests]# kubectl get pods
NAME                           READY   STATUS             RESTARTS   AGE
clinet                         1/1     Running            0          28h
nginx-test-67d85d447c-2phzb    1/1     Running            0          27h
nginx-test-67d85d447c-g7cr2    1/1     Running            0          27h
nginx-test-67d85d447c-j552t    1/1     Running            0          27h
nginx-test-67d85d447c-v7thb    1/1     Running            0          27h
nginx-test-67d85d447c-xx99k    1/1     Running            0          27h
pod-demo                       2/2     Running            0          83s
View Code

三、资源清单详细说明

1)镜像的获取的途径

资源配置清单:
    自主式POd资源
    
    资源的清单格式
        一级字段:apiVersion(group/version),kind,metadata(name,namespace,labels,annotations, ...),spec,status(只读)
    
    Pod资源
        spec.containers <[]object
        
        - name <string>
          image <string>
          imagePullPolicy <string>
             Always,Never,IfNotPresent
            备注:Always镜像总是从官网下载
                  Never 只从本地获取
                  IfNotPresent 本地从本地拿,没有就去官网
                  如果使用,镜像用latest版本,默认从官网获取
View Code

 示例

[root@k8s6 manifests]# cat pod-demo.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: pod-demo
  namespace: default
  labels:
    app: myapp
    tier: frontend
spec:
  containers:
  - name: myapp
    image: nginx:1.14-alpine
  - name: busybox
    image: busybox:latest
    imagePullPolicy: IfNotPresent
    command:
    - "/bin/sh"
    - "-c"
    - "sleep 3600"
View Code

2)暴露端口

[root@k8s6 manifests]# cat pod-demo.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: pod-demo
  namespace: default
  labels:
    app: myapp
    tier: frontend
spec:
  containers:
  - name: myapp
    image: nginx:1.14-alpine
    ports:
    - name: http
      containerPort: 80
    - name: https
      containerPort: 443
  - name: busybox
    image: busybox:latest
    imagePullPolicy: IfNotPresent
    command:
    - "/bin/sh"
    - "-c"
    - "sleep 3600" 
containerPort: 80

 四、修改镜像中的默认标签。根据标签查看镜像

修改镜像中的默认应用:
command,args
    https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/
标签:
    key=value
        key :字母、数字
        value: 可以为空,只能字母或数字开头及结尾,中间可使用

1)默认显示的查看的显示方式

[root@k8s6 ~]# kubectl get pods --show-labels
NAME                           READY   STATUS             RESTARTS   AGE    LABELS
nginx-deploy-79b598b88-pt9xq   0/1     ImagePullBackOff   0          2d3h   pod-template-hash=79b598b88,run=ngi
nginx-test-67d85d447c-brwb2    1/1     Running            0          2d3h   pod-template-hash=67d85d447c,run=ng
nginx-test-67d85d447c-l7xvs    1/1     Running            0          2d3h   pod-template-hash=67d85d447c,run=ng
nginx-test-67d85d447c-qmrrw    1/1     Running            0          2d3h   pod-template-hash=67d85d447c,run=ng
nginx-test-67d85d447c-rsmdt    1/1     Running            0          2d3h   pod-template-hash=67d85d447c,run=ng
nginx-test-67d85d447c-twk77    1/1     Running            0          2d3h   pod-template-hash=67d85d447c,releas
pod-demo                       2/2     Running            47         47h    app=myapp,tier=frontend
[root@k8s6 ~]# kubectl get pods -L app
NAME                           READY   STATUS             RESTARTS   AGE    APP
nginx-deploy-79b598b88-pt9xq   0/1     ImagePullBackOff   0          2d3h   
nginx-test-67d85d447c-brwb2    1/1     Running            0          2d3h   
nginx-test-67d85d447c-l7xvs    1/1     Running            0          2d3h   
nginx-test-67d85d447c-qmrrw    1/1     Running            0          2d3h   
nginx-test-67d85d447c-rsmdt    1/1     Running            0          2d3h   
nginx-test-67d85d447c-twk77    1/1     Running            0          2d3h   
pod-demo                       2/2     Running            47         47h    myapp
[root@k8s6 ~]# kubectl get pods -l app
NAME       READY   STATUS    RESTARTS   AGE
pod-demo   2/2     Running   47         47h
[root@k8s6 ~]# kubectl get pods -l app --show-labels
NAME       READY   STATUS    RESTARTS   AGE   LABELS
pod-demo   2/2     Running   47         47h   app=myapp,tier=frontend
View Code

 kubectl label --help   为资源打标签,查看帮助信息

2)给服务打标记

[root@k8s6 ~]# kubectl get pods -l app --show-labels
NAME       READY   STATUS    RESTARTS   AGE   LABELS
pod-demo   2/2     Running   47         47h   app=myapp,tier=frontend
[root@k8s6 ~]# kubectl label pods pod-demo release=stable --overwrite
pod/pod-demo labeled
[root@k8s6 ~]# kubectl get pods -l app --show-labels
NAME       READY   STATUS    RESTARTS   AGE   LABELS
pod-demo   2/2     Running   47         47h   app=myapp,release=stable,tier=frontend
kubectl label pods pod-demo release=stable --overwrite

3)一般标签选择器的使用

等值关系:=,==,!=
集合关系:
    KEY in (VALUE1,VALUE2,....)
    KEY notin (VALUE1,VALUE2,....)
    KEY
    !KEY

3.1)基本查询

[root@k8s6 ~]# kubectl get pods
NAME                           READY   STATUS             RESTARTS   AGE
nginx-deploy-79b598b88-pt9xq   0/1     ImagePullBackOff   0          2d3h
nginx-test-67d85d447c-brwb2    1/1     Running            0          2d3h
nginx-test-67d85d447c-l7xvs    1/1     Running            0          2d3h
nginx-test-67d85d447c-qmrrw    1/1     Running            0          2d3h
nginx-test-67d85d447c-rsmdt    1/1     Running            0          2d3h
nginx-test-67d85d447c-twk77    1/1     Running            0          2d3h
pod-demo                       2/2     Running            47         47h
[root@k8s6 ~]# kubectl get pods -l release
NAME                          READY   STATUS    RESTARTS   AGE
nginx-test-67d85d447c-twk77   1/1     Running   0          2d3h
pod-demo                      2/2     Running   47         47h
[root@k8s6 ~]# kubectl get pods -l release,app
NAME       READY   STATUS    RESTARTS   AGE
pod-demo   2/2     Running   47         47h
[root@k8s6 ~]# kubectl get pods -l release=stable
NAME       READY   STATUS    RESTARTS   AGE
pod-demo   2/2     Running   47         47h
[root@k8s6 ~]# kubectl get pods -l release=stable --show-labels
NAME       READY   STATUS    RESTARTS   AGE   LABELS
pod-demo   2/2     Running   47         47h   app=myapp,release=stable,tier=frontend
View Code

3.2)直接为pods节点服务器指定标签

[root@k8s6 ~]# kubectl get pods
NAME                           READY   STATUS             RESTARTS   AGE
nginx-deploy-79b598b88-pt9xq   0/1     ImagePullBackOff   0          2d3h
nginx-test-67d85d447c-brwb2    1/1     Running            0          2d3h
nginx-test-67d85d447c-l7xvs    1/1     Running            0          2d3h
nginx-test-67d85d447c-qmrrw    1/1     Running            0          2d3h
nginx-test-67d85d447c-rsmdt    1/1     Running            0          2d3h
nginx-test-67d85d447c-twk77    1/1     Running            0          2d3h
pod-demo                       2/2     Running            47         47h
[root@k8s6 ~]# kubectl label pods nginx-test-67d85d447c-twk77 relea=canary
pod/nginx-test-67d85d447c-twk77 labeled
[root@k8s6 ~]# kubectl get pods -l relea
NAME                          READY   STATUS    RESTARTS   AGE
nginx-test-67d85d447c-twk77   1/1     Running   0          2d3h
View Code

in和notin的用法

kubectl get pods -l "release in (canary,beta,alpha)"
kubectl get pods -l "release notin (canary,beta,alpha)"

4)内嵌字段的标签

节点默认标签
许多资源支持内嵌字段定义其使用标签选择器
matchLabels: 直接给定键值
matchExpressions: 基于给定的表达式来定义使用标签选择器,{key:"KEY",operator:"OPERATOR",value:[VALUE1,VALUE2,...]}
    操作符:
        In,Notin:values字段的值必须为非空列表
        Exists,NotExists:values 字段的值必须非空列表

示例

[root@k8s6 ~]# kubectl get nodes --show-labels
NAME     STATUS   ROLES    AGE     VERSION   LABELS
k8s6     Ready    master   5d18h   v1.13.3   beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,kubernetes.io/hostname=k8s6,node-role.kubernetes.io/master=
node01   Ready    <none>   5d17h   v1.13.3   beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,disktype=ssd,kubernetes.io/hostname=node01
node02   Ready    <none>   5d17h   v1.13.3   beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,kubernetes.io/hostname=node02
[root@k8s6 ~]# kubectl label nodes node02 disktype=ssddd
node/node02 labeled
[root@k8s6 ~]# kubectl get nodes --show-labels
NAME     STATUS   ROLES    AGE     VERSION   LABELS
k8s6     Ready    master   5d18h   v1.13.3   beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,kubernetes.io/hostname=k8s6,node-role.kubernetes.io/master=
node01   Ready    <none>   5d17h   v1.13.3   beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,disktype=ssd,kubernetes.io/hostname=node01
node02   Ready    <none>   5d17h   v1.13.3   beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,disktype=ssddd,kubernetes.io/hostname=node02
View Code

 后面根据nodeSelector算法,新建的容器规模都只会在这个标签下的主机建立服务

[root@k8s6 manifests]# cat pod-demo.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: pod-demo
  namespace: default
  labels:
    app: myapp
    tier: frontend
  annotations:
    blog.com/created-by: "cluster admin"
spec:
  containers:
  - name: myapp
    image: nginx:1.14-alpine
    ports:
    - name: http
      containerPort: 80
    - name: https
      containerPort: 443
  - name: busybox
    image: busybox:latest
    imagePullPolicy: IfNotPresent
    command:
    - "/bin/sh"
    - "-c"
    - "sleep 3600" 
  nodeSelector:
    disktype: ssdd
nodeSelector:

 5)annotations 描述该镜像是由谁创建的

[root@k8s6 manifests]# cat pod-demo.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: pod-demo
  namespace: default
  labels:
    app: myapp
    tier: frontend
  annotations:
    blog.com/created-by: "cluster admin"
spec:
  containers:
  - name: myapp
    image: nginx:1.14-alpine
    ports:
    - name: http
      containerPort: 80
    - name: https
      containerPort: 443
  - name: busybox
    image: busybox:latest
    imagePullPolicy: IfNotPresent
    command:
    - "/bin/sh"
    - "-c"
    - "sleep 3600" 
  nodeSelector:
    disktype: ssdd
annotations

kubectl describe pods pod-demo  查看详细描述信息

 五、k8s的探测行为

探针类型有三种
ExecAction、TCPSockerAction、HTTPGetAction

1)命令检测补充。test 命令

[root@k8s6 ~]# test -e aa
[root@k8s6 ~]# echo $?
1
[root@k8s6 ~]# touch aa
[root@k8s6 ~]# test -e aa
[root@k8s6 ~]# echo $?
0

命令探针使用。busybox镜像使用,测试存在问题

[root@k8s6 manifests]# kubectl create -f liveness-http.yaml

[root@k8s6 manifests]# cat liveness-exec.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: liveness-exec-pod
  namespace: default
spec:
  containers:
  - name: liveness-exec-container
    image: busybox:latest
    imagePullPolicy: IfNotPresent
    command: ["/bin/sh","-c","touch /tmp/healthy;sleep 30; rm -f /tmp/healthy;sleep 3600"]    
    livenessProbe:
      exec:
        command: ["test","-e","/tmp/healthy"]    # 探针命令,检测
      initialDelaySeconds: 1
      periodSeconds: 3
liveness-http.yaml

 2)http的方式检测

[root@k8s6 manifests]# cat liveness-http.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: liveness-httpget-pod
  namespace: default
spec:
  containers:
  - name: liveness-exec-container
    image: ikubernetes/myapp:v1
    imagePullPolicy: IfNotPresent
    ports:
    - name: http
      containerPort: 80
    livenessProbe:
      httpGet:
        port: http
        path: /index.html
      initialDelaySeconds: 1
      periodSeconds: 3
View Code

检测方式

[root@k8s6 ~]# kubectl exec -it liveness-httpget-pod -- /bin/sh        进入容器
/ # ls /usr/share/nginx/html/index.html        如果删除该文件,服务器会执行 curl 10.200.1.15 来检测该文件,如果没有,服务器会重启,来生成文件
/usr/share/nginx/html/index.html
/ # cat /usr/share/nginx/html/[root@node02 ~]# curl 10.200.1.15
Hello MyApp | Version: v1 | <a href="hostname.html">Pod Name</a>
<h1>hello world</h1>
index.html

[root@node02 ~]# curl 10.200.1.15
Hello MyApp | Version: v1 | <a href="hostname.html">Pod Name</a>
<h1>hello world</h1>

查看服务器是否重启过

[root@k8s6 manifests]# kubectl get pods
NAME                           READY   STATUS             RESTARTS   AGE
liveness-httpget-pod           1/1     Running            0          2m6s

# 可以看到服务器重启了一次
[root@k8s6 manifests]# kubectl get pods
NAME                           READY   STATUS             RESTARTS   AGE    
liveness-httpget-pod           1/1     Running            1          3m23s
View Code

 3)readinessProbe 探测。

如果删除了指定的index.html 文件,服务状态 变为不就绪状态。如果又创建该文件,服务器又自动变为就绪状态

[root@k8s6 manifests]# cat readiness-httpget.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: readiness-httpget-pod
  namespace: default
spec:
  containers:
  - name: readiness-httpget-container
    image: ikubernetes/myapp:v1
    imagePullPolicy: IfNotPresent
    ports:
    - name: http
      containerPort: 80
    readinessProbe:
      httpGet:
        port: http
        path: /index.html
      initialDelaySeconds: 1
      periodSeconds: 3
readinessProbe

该脚本检测到未就绪状态,并不会重启服务

六、脚本修改容器规模大小

1)定义服务的yaml文件,内部临时定义2个规模的大小

[root@k8s6 manifests]# cat rs-demo.yaml 
apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: myapp
  namespace: default
spec:
  replicas: 2
  selector:
    matchLabels:
      app: myapp
      release: canary
  template:
    metadata:
      name: myapp-pod
      labels:
        app: myapp
        release: canary
        environment: qa
    spec:
      containers:
      - name: myapp-container
        image: ikubernetes/myapp:v1
        ports:
        - name: http
          containerPort: 80
rs-demo.yaml

查看,目前2个规模

[root@k8s6 manifests]# kubectl create -f rs-demo.yaml 
replicaset.apps/myapp created
[root@k8s6 manifests]# kubectl get rs
NAME                     DESIRED   CURRENT   READY   AGE
myapp                    2         2         2       15s

使用  kubectl edit rs myapp  可编辑规模大小

[root@k8s6 ~]# kubectl edit rs myapp
................
  selfLink: /apis/extensions/v1beta1/namespaces/default/replicasets/myapp
  uid: 26caf59b-3dc3-11e9-8abb-000c2938db24
spec:
  replicas: 5
................

再次查看,则变为5个了

[root@k8s6 manifests]# kubectl get rs
NAME                     DESIRED   CURRENT   READY   AGE
myapp                    5         5         3       5m46s

2)另一种方式修改规模的大小。直接修改文件,kubectl apply -f rs-demo.yaml  检测文件的变化

[root@k8s6 manifests]# vim rs-demo.yaml 
[root@k8s6 manifests]# kubectl apply -f rs-demo.yaml 

kubectl get pods -l app=myapp -w  检测文件的变化

 3)以打补丁的方式修改规模大小

[root@k8s6 manifests]# cat rs-demo.yaml 
apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: myapp
  namespace: default
spec:
  replicas: 4
  selector:
    matchLabels:
      app: myapp
      release: canary
  template:
    metadata:
      name: myapp-pod
      labels:
        app: myapp
        release: canary
        environment: qa
    spec:
      containers:
      - name: myapp-container
        image: ikubernetes/myapp:v1
        ports:
        - name: http
          containerPort: 80
[root@k8s6 manifests]# kubectl get rs
NAME                     DESIRED   CURRENT   READY   AGE
myapp                    4         4         4       32m
nginx-deploy-79b598b88   1         1         0       4d10h
nginx-test-5bbfddf46b    0         0         0       4d10h
nginx-test-67d85d447c    5         5         5       4d9h
[root@k8s6 manifests]# kubectl patch ReplicaSet myapp -p '{"spec":{"replicas":5}}'
replicaset.extensions/myapp patched
[root@k8s6 manifests]# kubectl get rs
NAME                     DESIRED   CURRENT   READY   AGE
myapp                    5         5         5       32m
nginx-deploy-79b598b88   1         1         0       4d10h
nginx-test-5bbfddf46b    0         0         0       4d10h
nginx-test-67d85d447c    5         5         5       4d9h
View Code

4)补充以打补丁的方式修改内容

kubectl patch Deployment myapp-deploy -p '{"spec":{"strategy":{"rollingUpdate":{"maxSurge":1,"maxUnavailable":0}}}}'

描述信息

[root@k8s6 manifests]# kubectl describe deployment myapp-deploy
Name:                   myapp-deploy
Namespace:              default
CreationTimestamp:      Sun, 03 Mar 2019 23:24:22 +0800
Labels:                 app=myapp
                        release=canary
Annotations:            deployment.kubernetes.io/revision: 1
                        kubectl.kubernetes.io/last-applied-configuration:
                          {"apiVersion":"apps/v1","kind":"Deployment","metadata":{"annotations":{},"name":"myapp-deploy","namespace":"default"},"spec":{"replicas":2...
Selector:               app=myapp,release=canary
Replicas:               5 desired | 5 updated | 5 total | 5 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  0 max unavailable, 1 max surge
kubectl describe deployment myapp-deploy

六、查看滚动历史,回滚版本系统

1)编辑deploy-demp.yaml 指定kind: Deployment

[root@k8s6 manifests]# cat  deploy-demp.yaml 
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp-deploy
  namespace: default
spec:
  replicas: 2
  selector:
    matchLabels:
      app: myapp
      release: canary
  template:
    metadata:
      name: myapp
      labels:
        app: myapp
        release: canary
    spec:
      containers:
      - name: myapp-container
        image: ikubernetes/myapp:v1
        ports:
        - name: http
          containerPort: 80
deploy-demp.yaml

查看版本历史命令:kubectl rollout history deployment myapp-deploy

[root@k8s6 manifests]# kubectl apply -f  deploy-demp.yaml 
deployment.apps/myapp-deploy created
[root@k8s6 manifests]# kubectl get rs
NAME                      DESIRED   CURRENT   READY   AGE
myapp                     0         0         0       38m
myapp-deploy-6fdcbf595d   2         2         2       66s
nginx-deploy-79b598b88    1         1         0       4d10h
nginx-test-5bbfddf46b     0         0         0       4d10h
nginx-test-67d85d447c     5         5         5       4d9h
[root@k8s6 manifests]# kubectl rollout history deployment myapp-deploy
deployment.extensions/myapp-deploy 
REVISION  CHANGE-CAUSE
0         <none>
1         <none>
kubectl rollout history deployment myapp-deploy

 它的滚动方式为: kubectl patch Deployment myapp-deploy -p '{"spec":{"replicas":5}}'

注意需要了解他们的区别。

kind: Deployment
kind: ReplicaSet

 2)以打补丁的方式修改版本容器

kubectl set image deployment myapp-deploy myapp=ikubernetes/myapp:v3 && kubectl rollout pause deployment myapp-deploy

修改时,先更新一个容器服务就被暂停了,后面需要取消暂停,其他容器才会更新

kubectl get pods -l app=myapp -w   监控更新变化

kubectl rollout resume deployment myapp-deploy   取消之前的暂停,继续更新
kubectl get rs -o wide  可查看使用的镜像版本

3)回滚版本

[root@k8s6 manifests]# kubectl rollout history deployment myapp-deploy     查看历史版本
[root@k8s6 manifests]# kubectl rollout undo deployment myapp-deploy --to-revision=1     指定回到版本1

七、redis镜像的使用

redis镜像寻找地址:https://hub.docker.com/r/ikubernetes/filebeat/tags

先在节点拉取镜像:docker pull ikubernetes/filebeat:5.6.5-alpine

1)定义yaml文件(2个镜像内容)

[root@k8s6 manifests]# cat ds-demo.yaml 
apiVersion: apps/v1
kind: Deployment
metadata:
  name: redis
  namespace: default
spec:
  replicas: 1
  selector:
    matchLabels:
      app: redis
      role: logstor
  template:
    metadata:
      labels:
        app: redis
        role: logstor
    spec:
      containers:
      - name: redis
        image: redis:4.0-alpine
        ports:
        - name: redis
          containerPort: 6379
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: filebeat-ds
  namespace: default
spec:
  selector:
    matchLabels:
      app: filebeat
      release: stable
  template:
    metadata:
      labels:
        app: filebeat
        release: stable
    spec:
      containers:
      - name: filebeat
        image: ikubernetes/filebeat:5.6.5-alpine
        env:
        - name: REDIS_HOST
          value: redis.default.svc.cluster.local
        - name: REDOS_LOG_LEVEL
          value: info
ds-demo.yaml

创新该服务

[root@k8s6 manifests]# kubectl apply -f ds-demo.yaml 
deployment.apps/redis created
daemonset.apps/filebeat-ds created
[root@k8s6 manifests]# kubectl get pods -o wide
NAME                            READY   STATUS             RESTARTS   AGE     IP            NODE     NOMINATED NODE   READINESS GATES
filebeat-ds-9q792               1/1     Running            0          44s     10.200.1.26   node02   <none>           <none>
filebeat-ds-fw6r7               1/1     Running            0          44s     10.200.2.26   node01   <none>           <none>
redis-85b846ff9c-g8cdt          1/1     Running            0          44s     10.200.1.25   node02   <none>           <none>
[root@k8s6 manifests]# kubectl expose deployment redis --port=6379
service/redis exposed
[root@k8s6 manifests]# kubectl get svc
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE
kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP        6d1h
nginx        NodePort    10.107.169.145   <none>        80:31986/TCP   4d11h
redis        ClusterIP   10.99.49.232     <none>        6379/TCP       52s

 更新定义的filebeat-ds 镜像

[root@k8s6 manifests]# kubectl get ds
NAME          DESIRED   CURRENT   READY   UP-TO-DATE   AVAILABLE   NODE SELECTOR   AGE
filebeat-ds   2         2         2       2            2           <none>          22m
[root@k8s6 manifests]# kubectl get ds -o wide
NAME          DESIRED   CURRENT   READY   UP-TO-DATE   AVAILABLE   NODE SELECTOR   AGE   CONTAINERS   IMAGES                              SELECTOR
filebeat-ds   2         2         2       2            2           <none>          22m   filebeat     ikubernetes/filebeat:5.6.5-alpine   app=filebeat,release=stable
[root@k8s6 manifests]# kubectl set image daemonsets filebeat-ds filebeat=ikubernetes/filebeat:5.6.6-alpine
daemonset.extensions/filebeat-ds image updated
[root@k8s6 manifests]# kubectl get ds -o wide
NAME          DESIRED   CURRENT   READY   UP-TO-DATE   AVAILABLE   NODE SELECTOR   AGE   CONTAINERS   IMAGES                              SELECTOR
filebeat-ds   2         2         1       1            1           <none>          24m   filebeat     ikubernetes/filebeat:5.6.6-alpine   app=filebeat,release=stable
View Code

 

posted on 2019-04-16 15:11  可口_可乐  阅读(3171)  评论(0编辑  收藏  举报