01 Pod进阶学习之路

1.1 Lifecycle

官网https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/

  • 挂起(Pending):Pod 已被 Kubernetes 系统接受,但有一个或者多个容器镜像尚未创建。等待时间包括调度 Pod 的时间和通过网络下载镜像的时间,这可能需要花点时间。
  • 运行中(Running):该 Pod 已经绑定到了一个节点上,Pod 中所有的容器都已被创建。至少有一个容器正在运行,或者正处于启动或重启状态。
  • 成功(Succeeded):Pod 中的所有容器都被成功终止,并且不会再重启。
  • 失败(Failed):Pod 中的所有容器都已终止了,并且至少有一个容器是因为失败终止。也就是说,容器以非0状态退出或者被系统终止。
  • 未知(Unknown):因为某些原因无法取得 Pod 的状态,通常是因为与 Pod 所在主机通信失败。

1.2 重启策略

官网https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy

  1. A PodSpec has a restartPolicy field with possible values Always, OnFailure, and Never. The default value is Always. restartPolicy applies to all Containers in the Pod. restartPolicy only refers to restarts of the Containers by the kubelet on the same node. Exited Containers that are restarted by the kubelet are restarted with an exponential back-off delay (10s, 20s, 40s …) capped at five minutes, and is reset after ten minutes of successful execution. As discussed in the Pods document, once bound to a node, a Pod will never be rebound to another node.
  • Always:容器失效时,即重启
  • OnFailure:容器终止运行且退出码不为0时重启
  • Never:永远不重启

1.3 静态Pod

静态Pod是由kubelet进行管理的,并且存在于特定的Node上。

不能通过API Server进行管理,无法与ReplicationController,Ddeployment或者DaemonSet进行关联,也无法进行健康检查。

1.4 健康检查

官网https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#container-probes

The kubelet can optionally perform and react to three kinds of probes on running Containers:

  • livenessProbe: Indicates whether the Container is running. If the liveness probe fails, the kubelet kills the Container, and the Container is subjected to its restart policy. If a Container does not provide a liveness probe, the default state is Success.
  • readinessProbe: Indicates whether the Container is ready to service requests. If the readiness probe fails, the endpoints controller removes the Pod’s IP address from the endpoints of all Services that match the Pod. The default state of readiness before the initial delay is Failure. If a Container does not provide a readiness probe, the default state is Success.
  • startupProbe: Indicates whether the application within the Container is started. All other probes are disabled if a startup probe is provided, until it succeeds. If the startup probe fails, the kubelet kills the Container, and the Container is subjected to its restart policy. If a Container does not provide a startup probe, the default state is Success.

LivenessProbe探针:判断容器是否存活

ReadinessProbe探针:判断容器是否启动完成

1.5 ConfigMap

官网https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/

  1. ConfigMaps allow you to decouple configuration artifacts from image content to keep containerized applications portable.

说白了就是用来保存配置数据的键值对,也可以保存单个属性,也可以保存配置文件。

所有的配置内容都存储在etcd中,创建的数据可以供Pod使用。

1.5.1 命令行创建

  1. # 创建一个名称为my-config的ConfigMap,key值时db.port,value值是'3306'
  2. kubectl create configmap my-config --from-literal=db.port='3306'
  3. kubectl get configmap

详情信息:kubectl get configmap myconfig -o yaml

  1. apiVersion: v1
  2. data:
  3. db.port: "3306"
  4. kind: ConfigMap
  5. metadata:
  6. creationTimestamp: "2019-11-22T09:50:17Z"
  7. name: my-config
  8. namespace: default
  9. resourceVersion: "691934"
  10. selfLink: /api/v1/namespaces/default/configmaps/my-config
  11. uid: 7d4f338b-0d0d-11ea-bb46-00163e0edcbd

1.5.2 从配置文件中创建

创建一个文件,名称为app.properties

  1. name=jack
  2. age=17
  1. kubectl create configmap app --from-file=./app.properties
  2. kubectl get configmap
  3. kubectl get configmap app -o yaml

1.5.3 从目录中创建

  1. mkdir config
  2. cd config
  3. mkdir a
  4. mkdir b
  5. cd ..
  1. kubectl create configmap config --from-file=config/
  2. kubectl get configmap

1.5.4 通过yaml文件创建

configmaps.yaml

  1. apiVersion: v1
  2. kind: ConfigMap
  3. metadata:
  4. name: special-config
  5. namespace: default
  6. data:
  7. special.how: very
  8. ---
  9. apiVersion: v1
  10. kind: ConfigMap
  11. metadata:
  12. name: env-config
  13. namespace: default
  14. data:
  15. log_level: INFO
  1. kubectl apply -f configmaps.yaml
  2. kubectl get configmap

1.5.5 ConfigMap的使用

  • 使用方式
  1. (1)通过环境变量的方式,直接传递给pod
  2. 使用configmap中指定的key
  3. 使用configmap中所有的key
  4. (2)通过在pod的命令行下运行的方式(启动命令中)
  5. (3)作为volume的方式挂载到pod
  • 注意
  1. (1)ConfigMap必须在Pod使用它之前创建
  2. (2)使用envFrom时,将会自动忽略无效的键
  3. (3)Pod只能使用同一个命名空间的ConfigMap

1.5.5.1 通过环境变量使用

使用valueFrom、configMapKeyRef、name

key的话指定要用到的key

test-pod.yaml

kubectl logs pod-name

  1. apiVersion: v1
  2. kind: Pod
  3. metadata:
  4. name: dapi-test-pod
  5. spec:
  6. containers:
  7. - name: test-container
  8. image: busybox
  9. command: [ "/bin/sh", "-c", "env" ]
  10. env:
  11. # Define the environment variable
  12. - name: SPECIAL_LEVEL_KEY
  13. valueFrom:
  14. configMapKeyRef:
  15. # The ConfigMap containing the value you want to assign to SPECIAL_LEVEL_KEY
  16. name: special-config
  17. # Specify the key associated with the value
  18. key: special.how
  19. restartPolicy: Never

1.5.5.2 用作命令行参数

在命令行下引用时,需要先设置为环境变量,之后可以用过$(VAR_NAME)设置容器启动命令的启动参数

test-pod2.yaml

kubectl logs pod-name

  1. apiVersion: v1
  2. kind: Pod
  3. metadata:
  4. name: dapi-test-pod2
  5. spec:
  6. containers:
  7. - name: test-container
  8. image: busybox
  9. command: [ "/bin/sh", "-c", "echo $(SPECIAL_LEVEL_KEY)" ]
  10. env:
  11. - name: SPECIAL_LEVEL_KEY
  12. valueFrom:
  13. configMapKeyRef:
  14. name: special-config
  15. key: special.how
  16. restartPolicy: Never

1.5.5.3 作为volume挂载使用

将创建的ConfigMap直接挂载至Pod的/etc/config目录下,其中每一个key-value键值对都会生成一个文件,key为文件名,value为内容。

kubectl apply -f pod-myconfigmap-v2.yml

kubectl exec -it pod-name bash

kubectl logs pod-name

  1. apiVersion: v1
  2. kind: Pod
  3. metadata:
  4. name: pod-configmap2
  5. spec:
  6. containers:
  7. - name: test-container
  8. image: busybox
  9. command: [ "/bin/sh", "-c", "ls /etc/config/" ]
  10. volumeMounts:
  11. - name: config-volume
  12. mountPath: /etc/config
  13. volumes:
  14. - name: config-volume
  15. configMap:
  16. name: special-config
  17. restartPolicy: Never

1.5.6 ConfigMap在Ingress Controller中实战

在之前ingress网络中的mandatory.yaml文件中使用了ConfigMap,于是我们可以打开

可以发现有nginx-configuration、tcp-services等名称的cm

而且也可以发现最后在容器的参数中使用了这些cm

  1. containers:
  2. - name: nginx-ingress-controller
  3. image: quay.io/kubernetes-ingress-controller/nginx-ingress-controller:0.26.1
  4. args:
  5. - /nginx-ingress-controller
  6. - --configmap=$(POD_NAMESPACE)/nginx-configuration
  7. - --tcp-services-configmap=$(POD_NAMESPACE)/tcp-services
  8. - --udp-services-configmap=$(POD_NAMESPACE)/udp-services
  9. - --publish-service=$(POD_NAMESPACE)/ingress-nginx
  10. - --annotations-prefix=nginx.ingress.kubernetes.io

开启证明之旅和cm的使用方式

(1)查看nginx ingress controller的pod部署

kubectl get pods -n ingress-nginx -o wide

  1. NAME READY STATUS RESTARTS AGE
  2. nginx-ingress-controller-7c66dcdd6c-v8grg 1/1 Running 0 8d
  3. NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
  4. nginx-ingress-controller-7c66dcdd6c-v8grg 1/1 Running 0 8d 172.16.31.150 w1 <none> <none>

(2)发现运行在w1节点上,说明w1上一定有对应的container,来到w1节点

docker ps | grep ingress

  1. ddde4b354852 quay.io/kubernetes-ingress-controller/nginx-ingress-controller "/usr/bin/dumb-init …" 8 days ago Up 8 days k8s_nginx-ingress-controller_nginx-ingress-controller-7c66dcdd6c-v8grg_ingress-nginx_b3e2f9a5-0943-11ea-b2b3-00163e0edcbd_0
  2. b6b7412855c5 k8s.gcr.io/pause:3.1 "/pause" 8 days ago Up 8 days k8s_POD_nginx-ingress-controller-7c66dcdd6c-v8grg_ingress-nginx_b3e2f9a5-0943-11ea-b2b3-00163e0edcbd_0

(3)不妨进入容器看看?

docker exec -it ddde4b354852 bash

(4)可以发现,就是一个nginx嘛,而且里面还有nginx.conf文件,美滋滋

  1. /etc/nginx/nginx.conf

(5)不妨打开nginx.conf文件看看

假如已经配置过ingress,不妨尝试搜索一下”k8s.demoxxx”/“itcrazy2016.com”

  1. server {
  2. server_name k8s.itcrazy2016.com ;

(6)到这里,大家应该有点感觉了,原来nginx ingress controller就是一个nginx,而所谓的ingress.yaml文件中配置的内容像itcrazy2016.com就会对应到nginx.conf中。

(7)但是,不可能每次都进入到容器里面来修改,而且还需要手动重启nginx,很麻烦

一定会有好事之者来做这件事情,比如在K8s中有对应的方式,修改了什么就能修改nginx.conf文件

(8)先查看一下nginx.conf文件中的内容,比如找个属性:proxy_connect_timeout 5s

我们想要将这个属性在K8s中修改成8s,可以吗?

kubectl get cm -n ingress-nginx

网盘/课堂源码/nginx-config.yaml

kubectl apply -f nginx-config.yaml

kubectl get cm -n ingress-nginx

  1. kind: ConfigMap
  2. apiVersion: v1
  3. metadata:
  4. name: nginx-configuration
  5. namespace: ingress-nginx
  6. labels:
  7. app: ingress-nginx
  8. data:
  9. proxy-read-timeout: "208"

(9)再次查看nginx.conf文件

(10)其实定义规则都在nginx ingress controller的官网中

https://kubernetes.github.io/ingress-nginx/

https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/

1.6 Secret

官网https://kubernetes.io/docs/concepts/configuration/secret/

  1. Kubernetes secret objects let you store and manage sensitive information, such as passwords, OAuth tokens, and ssh keys.

1.6.1 Secret类型

  • Opaque:使用base64编码存储信息,可以通过base64 --decode解码获得原始数据,因此安全性弱。
  • kubernetes.io/dockerconfigjson:用于存储docker registry的认证信息。
  • kubernetes.io/service-account-token:用于被 serviceaccount 引用。serviceaccout 创建时 Kubernetes 会默认创建对应的 secret。Pod 如果使用了 serviceaccount,对应的 secret 会自动挂载到 Pod 的 /run/secrets/kubernetes.io/serviceaccount 目录中。

1.6.2 Opaque Secret

Opaque类型的Secret的value为base64位编码后的值

1.6.2.1 从文件中创建
  1. echo -n "admin" > ./username.txt
  2. echo -n "1f2d1e2e67df" > ./password.txt
  1. kubectl create secret generic db-user-pass --from-file=./username.txt --from-file=./password.txt
  1. kubectl get secret

1.6.2.2 使用yaml文件创建

(1)对数据进行64位编码

  1. echo -n 'admin' | base64
  2. echo -n '1f2d1e2e67df' | base64

(2)定义mysecret.yaml文件

  1. apiVersion: v1
  2. kind: Secret
  3. metadata:
  4. name: mysecret
  5. type: Opaque
  6. data:
  7. username: YWRtaW4=
  8. password: MWYyZDFlMmU2N2Rm

(3)根据yaml文件创建资源并查看

  1. kubectl create -f ./secret.yaml
  2. kubectl get secret
  3. kubectl get secret mysecret -o yaml

1.6.3 Secret使用

  • 以Volume方式
  • 以环境变量方式

1.6.3.1 将Secret挂载到Volume中

kubectl apply -f mypod.yaml

  1. apiVersion: v1
  2. kind: Pod
  3. metadata:
  4. name: mypod
  5. spec:
  6. containers:
  7. - name: mypod
  8. image: redis
  9. volumeMounts:
  10. - name: foo
  11. mountPath: "/etc/foo"
  12. readOnly: true
  13. volumes:
  14. - name: foo
  15. secret:
  16. secretName: mysecret
  1. kubectl exec -it pod-name bash
  2. ls /etc/foo
  3. cat /etc/foo/username
  4. cat /etc/foo/password

1.6.3.2 将Secret设置为环境变量
  1. apiVersion: v1
  2. kind: Pod
  3. metadata:
  4. name: secret-env-pod
  5. spec:
  6. containers:
  7. - name: mycontainer
  8. image: redis
  9. env:
  10. - name: SECRET_USERNAME
  11. valueFrom:
  12. secretKeyRef:
  13. name: mysecret
  14. key: username
  15. - name: SECRET_PASSWORD
  16. valueFrom:
  17. secretKeyRef:
  18. name: mysecret
  19. key: password
  20. restartPolicy: Never

1.6.4 kubernetes.io/dockerconfigjson

kubernetes.io/dockerconfigjson用于存储docker registry的认证信息,可以直接使用kubectl create secret命令创建

1.6.5 kubernetes.io/service-account-token

用于被 serviceaccount 引用。

serviceaccout 创建时 Kubernetes 会默认创建对应的 secret。Pod 如果使用了 serviceaccount,对应的 secret 会自动挂载到 Pod 的 /run/secrets/kubernetes.io/serviceaccount 目录中。

  1. kubectl get secret # 可以看到service-account-token
  2. kubectl run nginx --image nginx
  3. kubectl get pods
  4. kubectl exec -it nginx-pod-name bash
  5. ls /run/secrets/kubernetes.io/serviceaccount
  1. kubectl get secret
  2. kubectl get pods pod-name -o yaml
  3. # 找到volumes选项,定位到-name,secretName
  4. # 找到volumeMounts选项,定位到mountPath: /var/run/secrets/kubernetes.io/serviceaccount

小结:无论是ConfigMap,Secret,还是DownwardAPI,都是通过ProjectedVolume实现的,可以通过APIServer将信息放到Pod中进行使用。

1.7 指定Pod所运行的Node

(1)给node打上label

  1. kubectl get nodes
  2. kubectl label nodes worker02-kubeadm-k8s name=jack

(2)查看node是否有上述label

  1. kubectl describe node worker02-kubeadm-k8s

(3)部署一个mysql的pod

vi mysql-pod.yaml

  1. apiVersion: v1
  2. kind: ReplicationController
  3. metadata:
  4. name: mysql-rc
  5. labels:
  6. name: mysql-rc
  7. spec:
  8. replicas: 1
  9. selector:
  10. name: mysql-pod
  11. template:
  12. metadata:
  13. labels:
  14. name: mysql-pod
  15. spec:
  16. nodeSelector:
  17. name: jack
  18. containers:
  19. - name: mysql
  20. image: mysql
  21. imagePullPolicy: IfNotPresent
  22. ports:
  23. - containerPort: 3306
  24. env:
  25. - name: MYSQL_ROOT_PASSWORD
  26. value: "mysql"
  27. ---
  28. apiVersion: v1
  29. kind: Service
  30. metadata:
  31. name: mysql-svc
  32. labels:
  33. name: mysql-svc
  34. spec:
  35. type: NodePort
  36. ports:
  37. - port: 3306
  38. protocol: TCP
  39. targetPort: 3306
  40. name: http
  41. nodePort: 32306
  42. selector:
  43. name: mysql-pod

(4)查看pod运行详情

  1. kubectl apply -f mysql-pod.yaml
  2. kubectl get pods -o wide

02 Controller进阶学习之路

既然学习了Pod进阶,对于管理Pod的Controller肯定也要进阶一下,之前我们已经学习过的Controller有RC、RS和Deployment,除此之外还有吗?

官网https://kubernetes.io/docs/concepts/architecture/controller/

2.1 Job & CronJob

2.1.1 Job

官网https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/

  1. A Job creates one or more Pods and ensures that a specified number of them successfully terminate. As pods successfully complete, the Job tracks the successful completions. When a specified number of successful completions is reached, the task (ie, Job) is complete. Deleting a Job will clean up the Pods it created.

对于RS,RC之类的控制器,能够保持Pod按照预期数目持久地运行下去,它们针对的是持久性的任务,比如web服务。

而有些操作其实不需要持久,比如压缩文件,我们希望任务完成之后,Pod就结束运行,不需要保持在系统中,此时就需要用到Job。

所以可以这样理解,Job是对RS、RC等持久性控制器的补充。

负责批量处理短暂的一次性任务,仅执行一次,并保证处理的一个或者多个Pod成功结束。

Have a try

Here is an example Job config. It computes π to 2000 places and prints it out. It takes around 10s to complete.

  1. apiVersion: batch/v1
  2. kind: Job
  3. metadata:
  4. name: job-demo
  5. spec:
  6. template:
  7. metadata:
  8. name: job-demo
  9. spec:
  10. restartPolicy: Never
  11. containers:
  12. - name: counter
  13. image: busybox
  14. command:
  15. - "bin/sh"
  16. - "-c"
  17. - "for i in 9 8 7 6 5 4 3 2 1; do echo $i; done"

kubectl apply -f job.yaml

kubectl describe jobs/pi

kubectl logs pod-name

  • 非并行Job:

    • 通常只运行一个Pod,Pod成功结束Job就退出。
  • 固定完成次数的并行Job:

    • 并发运行指定数量的Pod,直到指定数量的Pod成功,Job结束。
  • 带有工作队列的并行Job:

    • 用户可以指定并行的Pod数量,当任何Pod成功结束后,不会再创建新的Pod
    • 一旦有一个Pod成功结束,并且所有的Pods都结束了,该Job就成功结束。
    • 一旦有一个Pod成功结束,其他Pods都会准备退出。

2.1.2 CronJob

官网https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/

``` A Cron Job creates Jobs on a time-based schedule.

One CronJob object is like one line of a crontab (cron table) file. It runs a job periodically on a given schedule, written in Cron format.

  1. > cronJob是基于时间进行任务的定时管理。
  2. - 在特定的时间点运行任务
  3. - 反复在指定的时间点运行任务:比如定时进行数据库备份,定时发送电子邮件等等。
  4. <a name="8bec5d30"></a>
  5. ### 2.2 StatefulSet
  6. > `官网`:[https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/](https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/)
  7. >

StatefulSet is the workload API object used to manage stateful applications.

Manages the deployment and scaling of a set of Pods, and provides guarantees about the ordering and uniqueness of these Pods.

  1. > - Stable, unique network identifiers.
  2. > - Stable, persistent storage.
  3. > - Ordered, graceful deployment and scaling.
  4. > - Ordered, automated rolling updates.
  5. >
  6. ---
  7. > 之前接触的Pod的管理对象比如RCDeploymentDaemonSetJob都是面向无状态的服务,但是现实中有很多服务是有状态的,比如MySQL集群、MongoDB集群、ZK集群等,它们都有以下共同的特点:
  8. > - 每个节点都有固定的ID,通过该ID,集群中的成员可以互相发现并且通信
  9. > - 集群的规模是比较固定的,集群规模不能随意变动
  10. > - 集群里的每个节点都是有状态的,通常会持久化数据到永久存储中
  11. > - 如果磁盘损坏,则集群里的某个节点无法正常运行,集群功能受损
  12. > 而之前的RC/Deployment没办法满足要求,所以从Kubernetes v1.4版本就引入了PetSet资源对象,在v1.5版本时更名为StatefulSet。从本质上说,StatefulSet可以看作是Deployment/RC对象的特殊变种
  13. > - StatefulSet里的每个Pod都有稳定、唯一的网络标识,可以用来发现集群内其他的成员
  14. > - Pod的启动顺序是受控的,操作第nPod时,前n-1Pod已经是运行且准备好的状态
  15. > - StatefulSet里的Pod采用稳定的持久化存储卷,通过PV/PVC来实现,删除Pod时默认不会删除与StatefulSet相关的存储卷
  16. > - StatefulSet需要与Headless Service配合使用
  17. **Have a try**
  18. > kubectl apply nginx-st.yaml
  19. > watch kubectl get pods # 观察pod的创建顺序,以及pod的名字
  20. ```yaml
  21. # 定义Service
  22. apiVersion: v1
  23. kind: Service
  24. metadata:
  25. name: nginx
  26. labels:
  27. app: nginx
  28. spec:
  29. ports:
  30. - port: 80
  31. name: web
  32. clusterIP: None
  33. selector:
  34. app: nginx
  35. ---
  36. # 定义StatefulSet
  37. apiVersion: apps/v1
  38. kind: StatefulSet
  39. metadata:
  40. name: web
  41. spec:
  42. selector:
  43. matchLabels:
  44. app: nginx
  45. serviceName: "nginx"
  46. replicas: 3
  47. template:
  48. metadata:
  49. labels:
  50. app: nginx
  51. spec:
  52. terminationGracePeriodSeconds: 10
  53. containers:
  54. - name: nginx
  55. image: nginx
  56. ports:
  57. - containerPort: 80
  58. name: web

2.3 DaemonSet

官网https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/

  1. A DaemonSet ensures that all (or some) Nodes run a copy of a Pod. As nodes are added to the cluster, Pods are added to them. As nodes are removed from the cluster, those Pods are garbage collected. Deleting a DaemonSet will clean up the Pods it created.

DaemonSet应用场景

  • 运行集群存储 daemon,例如在每个节点上运行 glusterdceph
  • 在每个节点上运行日志收集 daemon,例如fluentdlogstash
  • 在每个节点上运行监控 daemon,例如 Prometheus Node Exportercollectd、Datadog 代理、New Relic 代理,或 Ganglia gmond

2.4 Horizontal Pod Autoscaler

官网https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/

  1. The Horizontal Pod Autoscaler automatically scales the number of pods in a replication controller, deployment or replica set based on observed CPU utilization (or, with custom metrics support, on some other application-provided metrics). Note that Horizontal Pod Autoscaling does not apply to objects that cant be scaled, for example, DaemonSets.

使用Horizontal Pod Autoscaling,Kubernetes会自动地根据观察到的CPU利用率(或者通过一些其他应用程序提供的自定义的指标)自动地缩放在replication controller、deployment或replica set上pod的数量。

(0)前期准备

kubectl apply -f nginx-deployment.yaml

  1. apiVersion: apps/v1
  2. kind: Deployment
  3. metadata:
  4. name: nginx-deployment
  5. labels:
  6. app: nginx
  7. spec:
  8. replicas: 3
  9. selector:
  10. matchLabels:
  11. app: nginx
  12. template:
  13. metadata:
  14. labels:
  15. app: nginx
  16. spec:
  17. containers:
  18. - name: nginx
  19. image: nginx
  20. ports:
  21. - containerPort: 80

(1)创建hpa

  1. # 使nginx pod的数量介于2和10之间,CPU使用率维持在50%
  2. kubectl autoscale deployment nginx-deployment --min=2 --max=10 --cpu-percent=50

(2)查看所有创建的资源

  1. kubectl get pods
  2. kubectl get deploy
  3. kubectl get hpa

(3)修改replicas值为1或者11

可以发现最终最小还是2,最大还是10

  1. kubectl edit deployment nginx-deployment

(4)再次理解什么是hpa

  1. Horizontal Pod Autoscaling可以根据CPU使用率或应用自定义metrics自动扩展Pod数量(支持replication controllerdeploymentreplica set
  1. 01-控制管理器每隔30s查询metrics的资源使用情况
  2. 02-通过kubectl创建一个horizontalPodAutoscaler对象,并存储到etcd
  3. 03-APIServer:负责接受创建hpa对象,然后存入etcd

03 Resource和Dashboard

3.1 Resource

因为K8S的最小操作单元是Pod,所以这里主要讨论的是Pod的资源

官网https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/

在K8S的集群中,Node节点的资源信息会上报给APIServer

requests&limits

可以通过这两个属性设置cpu和内存

  1. When Containers have resource requests specified, the scheduler can make better decisions about which nodes to place Pods on. And when Containers have their limits specified, contention for resources on a node can be handled in a specified manner.
  1. apiVersion: v1
  2. kind: Pod
  3. metadata:
  4. name: frontend
  5. spec:
  6. containers:
  7. - name: db
  8. image: mysql
  9. env:
  10. - name: MYSQL_ROOT_PASSWORD
  11. value: "password"
  12. resources:
  13. requests:
  14. memory: "64Mi" # 表示64M需要内存
  15. cpu: "250m" # 表示需要0.25核的CPU
  16. limits:
  17. memory: "128Mi"
  18. cpu: "500m"
  19. - name: wp
  20. image: wordpress
  21. resources:
  22. requests:
  23. memory: "64Mi"
  24. cpu: "250m"
  25. limits:
  26. memory: "128Mi"
  27. cpu: "500m"

3.2 Dashboard

官网https://kubernetes.io/docs/tasks/access-application-cluster/web-ui-dashboard/

  1. Dashboard is a web-based Kubernetes user interface. You can use Dashboard to deploy containerized applications to a Kubernetes cluster, troubleshoot your containerized application, and manage the cluster resources. You can use Dashboard to get an overview of applications running on your cluster, as well as for creating or modifying individual Kubernetes resources (such as Deployments, Jobs, DaemonSets, etc). For example, you can scale a Deployment, initiate a rolling update, restart a pod or deploy new applications using a deploy wizard.

(1)根据yaml文件创建资源

网盘/课堂源码/dashboard.yaml

kubectl apply -f dashboard.yaml

(2)查看资源

  1. kubectl get pods -n kube-system
  2. kubectl get pods -n kube-system -o wide
  3. kubectl get svc -n kube-system
  4. kubectl get deploy kubernetes-dashboard -n kube-system

(3)使用火狐浏览器访问

  1. https://121.41.10.13:30018/

(4)生成登录需要的token

  1. # 创建service account
  2. kubectl create sa dashboard-admin -n kube-system
  3. # 创建角色绑定关系
  4. kubectl create clusterrolebinding dashboard-admin --clusterrole=cluster-admin --serviceaccount=kube-system:dashboard-admin
  5. # 查看dashboard-admin的secret名字
  6. ADMIN_SECRET=$(kubectl get secrets -n kube-system | grep dashboard-admin | awk '{print $1}')
  7. echo ADMIN_SECRET
  8. # 打印secret的token
  9. kubectl describe secret -n kube-system ${ADMIN_SECRET} | grep -E '^token' | awk '{print $2}'