k8s的基本使用

1、kubectl的命令參數html

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

[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 查看幫助linux

[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)進入交互式的容器服務nginx

[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)跑服務,但僅在容器內所在宿主機內能夠被訪問git

運行容器服務
[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官網下載,容器規模爲1golang

 3)暴露端口,查看幫助redis

[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)查看服務的詳細信息docker

[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)更改服務的規模shell

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/

 2、以資源的方式建立資源

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

3、資源清單詳細說明

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

 4、修改鏡像中的默認標籤。根據標籤查看鏡像

修改鏡像中的默認應用:
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  查看詳細描述信息

 5、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

該腳本檢測到未就緒狀態,並不會重啓服務

6、腳本修改容器規模大小

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

6、查看滾動歷史,回滾版本系統

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

7、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
相關文章
相關標籤/搜索