Pod是kubernetes的最小管理单元,在kubernetes中,按照pod的创建方式可以将其分为两类:
(1)自主式pod:kubernetes直接创建出来的Pod,这种pod删除后就没有了,也不会重建
(2)控制器创建的pod:kubernetes通过控制器创建的pod,这种pod删除了之后还会自动重建
Pod控制器,又称之为工作负载 (workload),是用于实现管理pod的中间层,确保pod资源符合预期的状态,pod的资源出现故障时,会尝试进行重启,当根据重启策略无效,则会重新新建pod的资源。
①代用户创建指定数量的pod副本,确保pod副本数量符合预期状态,并且支持滚动式自动扩容和缩容功能。取代了原始的ReplicationControllerpod控制器
②ReplicaSet主要三个组件组成:
①工作在ReplicaSet之上,用于管理无状态应用,目前来说最好的控制器,支持滚动更新和回滚功能,还提供声明式配置。
②ReplicaSet 与Deployment 这两个资源对象逐步替换之前RC的作用。
①用于确保集群中的每一个节点只运行特定的pod副本,通常用于实现系统级后台任务。比如ELK服务
②特性: 服务是无状态的,用于监控服务
③服务必须是守护进程
①管理有状态应用
②例如mysql服务
一次性的任务,只要完成就立即退出不需要重启或重建
周期性任务控制,创建的pod 不需要持续后台运行
在集群管理和运行容器的 pod 对象,pod 通过 label-selector 相关联
Pod 通过控制器实现应用的运维,如伸缩,升级等。
为了更好的解决服务编排的问题,kubernetes在V1.2版本开始,引入了Deployment控制器。值得一提的是,这种控制器并不直接管理pod,而是通过管理ReplicaSet来简介管理Pod,即:Deployment管理ReplicaSet,ReplicaSet管理Pod。所以Deployment比ReplicaSet功能更加强大。
示例需要在创建完pv和pvc基础上做,既是nfs-client-provisioner.yaml、nfs-client-rbac.yaml、nfs-client-storageclass.yaml三个得安装
用于部署无状态应用:微服务spingboud,维护副本数量
管理Pod和ReplicaSet
具有上线部署、副本设定、滚动升级、回滚等功能
提供声明式更新,例如只更新一个新的image
应用场景: web服务
mkdir /opt/pod
cd /opt/pod/
#空跑nginx的yaml文件
kubectl create deployment nginx-demo1 --image=nginx:1.15 --port=80 --replicas=3 --dry-run=client -oyaml > nginx-deployment.yaml
vim nginx-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: nginx-demo1
name: nginx-demo1
spec:
replicas: 3
selector:
matchLabels:
app: nginx-demo1
template:
metadata:
labels:
app: nginx-demo1
spec:
containers:
- image: nginx:1.15
name: nginx
ports:
- containerPort: 80
kubectl create -f nginx-deployment.yaml
kubectl get pods,deploy,rs
#查看控制器配置
kubectl edit deployment/nginx-demo1
apiVersion: apps/v1
kind: Deployment
metadata:
annotations:
deployment.kubernetes.io/revision: "1"
creationTimestamp: "2021-04-19T08:13:50Z"
generation: 1
labels:
app: nginx #Deployment资源的标签
name: nginx-deployment
namespace: default
resourceVersion: "167208"
selfLink: /apis/extensions/v1beta1/namespaces/default/deployments/nginx-deployment
uid: d9d3fef9-20d2-4196-95fb-0e21e65af24a
spec:
progressDeadlineSeconds: 600
replicas: 3 #期望的pod数量,默认是1
revisionHistoryLimit: 10
selector:
matchLabels:
app: nginx
strategy:
rollingUpdate:
maxSurge: 25% #升级过程中会先启动的新Pod的数量不超过期望的Pod数量的25%,也可以是一个绝对值
maxUnavailable: 25% #升级过程中在新的Pod启动好后销毁的旧Pod的数量不超过期望的Pod数量的25%,也可以是一个绝对值
type: RollingUpdate #滚动升级
template:
metadata:
creationTimestamp: null
labels:
app: nginx #Pod副本关联的标签
spec:
containers:
- image: nginx:1.15.4 #镜像名称
imagePullPolicy: IfNotPresent #镜像拉取策略
name: nginx
ports:
- containerPort: 80 #容器暴露的监听端口
protocol: TCP
resources: {}
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
dnsPolicy: ClusterFirst
restartPolicy: Always #容器重启策略
schedulerName: default-scheduler
securityContext: {}
terminationGracePeriodSeconds: 30
......
K8S中nginx服务升级版本——配置文件升级
#查看历史版本
kubectl rollout history deployment/nginx-demo1
deployment.apps/nginx-demo1
REVISION CHANGE-CAUSE
1
#查看版本
kubectl get pod -owide
curl -I 10.244.1.16
#配置文件里面修改版本
kubectl edit deployment.apps nginx-demo1
#查看升级后的版本
kubectl get pod -owide
curl -I 10.244.1.17
k8s服务回滚
#查看目前有几个回滚
kubectl rollout history deployment/nginx-demo1
#回滚
kubectl rollout undo deployment nginx-demo1
kubectl get pod -owide
curl -I 10.244.2.13
K8S中nginx服务升级版本——直接更新pod(在副本里面单独升级)
kubectl edit pod nginx-demo1-b8678b89c-2l2d5
部署有状态应用
稳定的持久化存储,即Pod重新调度后还是能访问到相同的持久化数据,基于PVC来实现
稳定的网络标志,即Pod重新调后其PodName和HostName不变,基于**Headless (没有IP只有DNS主机解析名,无头服务pod名称是唯一的标识不会变)**Service (即没有cluster IP的Service)来实现
有序部署(一个一个部署从0到n-1启动一个个部署),有序扩展,即Pod是有顺序的,在部署或者扩展的时候要依据定义的顺序依次进行(即从0到N-1,在下一个Pod运行之前所有之前的Pod必须都是Running和Ready状态),基于init containers来实现
有序收缩,有序删除 (是倒序即从N-1到0)
常见的应用场景: 数据库
https://kubernetes,io/docs/concepts/workloads/controllers/statefulset/
如mysq和Tomcat先启动mysql
vim svc.yaml
apiVersion: v1
kind: Service
metadata:
labels:
app: sts-svc
name: sts-svc
namespace: default
spec:
clusterIP: None
ports:
- name: http
port: 80
protocol: TCP
targetPort: 80
selector:
app: myapp-sts
type: ClusterIP
kubectl apply -f svc.yaml
kubectl get svc
apiVersion: v1
kind: Service
metadata:
name: nginx
labels:
app: nginx
spec:
ports:
- port: 80
name: web
clusterIP: None
selector:
app: nginx
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: web
spec:
selector:
matchLabels:
app: nginx # has to match .spec.template.metadata.labels
serviceName: "nginx"
replicas: 3 # by default is 1
template:
metadata:
labels:
app: nginx # has to match .spec.selector.matchLabels
spec:
terminationGracePeriodSeconds: 10
containers:
- name: nginx
image: k8s.gcr.io/nginx-slim:0.8
ports:
- containerPort: 80
name: web
volumeMounts:
- name: www
mountPath: /usr/share/nginx/html
volumeClaimTemplates:
- metadata:
name: www
spec:
accessModes: [ "ReadWriteOnce" ]
storageClassName: "my-storage-class"
resources:
requests:
storage: 1Gi
从上面的应用场景可以发现,StatefulSet由以下几个部分组成:
●Headless Service(无头服务):用于为Pod资源标识符生成可解析的DNS记录。 DNS
●volumeClaimTemplates(存储卷申请模板):基于静态或动态PV供给方式为Pod资源提供专有的固定存储。
●StatefulSet:用于管控Pod资源。
在deployment中,每一个pod是没有名称,是随机字符串,是无序的。
而statefulset中是要求有序的,每一个pod的名称必须是固定的。
当节点挂了,重建之后的标识符是不变的,每一个节点的节点名称是不能改变的。pod名称是作为pod识别的唯一标识符,必须保证其标识符的稳定并且唯一。
为了实现标识符的稳定,这时候就需要一个headless service 解析直达到pod,还需要给pod配置一个唯一的名称。
大部分有状态副本集都会用到持久存储,比如分布式系统来说,由于数据是不一样的,每个节点都需要自己专用的存储节点。而在 deployment中pod模板中创建的存储卷是一个共享的存储卷,多个pod使用同一个存储卷,而statefulset定义中的每一个pod都不能使用同一个存储卷,由此基于pod模板创建pod是不适应的,这就需要引入volumeClainTemplate,当在使用statefulset创建pod时,会自动生成一个PVC,从而请求绑定一个PV,从而有自己专用的存储卷。
服务发现:就是应用服务之间相互定位的过程。
应用场景:
●动态性强:Pod会飘到别的node节点
●更新发布频繁:互联网思维小步快跑,先实现再优化,老板永远是先上线再慢慢优化,先把idea变成产品挣到钱然后再慢慢一点一点优化
●支持自动伸缩:一来大促,肯定是要扩容多个副本
K8S里服务发现的方式—DNS,使K8S集群能够自动关联Service资源的“名称”和“CLUSTER-IP”,从而达到服务被集群自动发现的目的。
●skyDNS:Kubernetes 1.3之前的版本
●kubeDNS:Kubernetes 1.3至Kubernetes 1.11
●CoreDNS:Kubernetes 1.11开始至今
方法一:
下载链接:https://github.com/kubernetes/kubernetes/blob/master/cluster/addons/dns/coredns/coredns.yaml.base
vim transforms2sed.sed
s/__DNS__SERVER__/10.0.0.2/g
s/__DNS__DOMAIN__/cluster.local/g
s/__DNS__MEMORY__LIMIT__/170Mi/g
s/__MACHINE_GENERATED_WARNING__/Warning: This is a file generated from the base underscore template file: coredns.yaml.base/g
sed -f transforms2sed.sed coredns.yaml.base > coredns.yaml
方法二:上传 coredns.yaml 文件,如果是kubeadm搭建的K8S就不用上传文件,部署的时候已经安装好了
#查看是否安装coredns
kubectl get pods -n kube-system
#如没安装上传并创建
kubectl create -f coredns.yaml
vim nginx-service.yaml
apiVersion: v1
kind: Service
metadata:
name: nginx-service
labels:
app: nginx
spec:
type: NodePort
ports:
- port: 80
targetPort: 80
selector:
app: nginx
#创建
kubectl create -f nginx-service.yaml
#查看
kubectl get svc
vim pod6.yaml
apiVersion: v1
kind: Pod
metadata:
name: dns-test
spec:
containers:
- name: busybox
image: busybox:1.28.4
args:
- /bin/sh
- -c
- sleep 36000
restartPolicy: Never
kubectl create -f pod6.yaml
kubectl get pod
#解析kubernetes和nginx-service名称
[root@master01 pod]# kubectl exec -it dns-test sh
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.
/ # nslookup kubernetes
Server: 10.96.0.10
Address 1: 10.96.0.10 kube-dns.kube-system.svc.cluster.local
Name: kubernetes
Address 1: 10.96.0.1 kubernetes.default.svc.cluster.local
/ # nslookup nginx-service
Server: 10.96.0.10
Address 1: 10.96.0.10 kube-dns.kube-system.svc.cluster.local
Name: nginx-service
Address 1: 10.96.116.27 nginx-service.default.svc.cluster.local
kubectl explain statefulset
KIND: StatefulSet
VERSION: apps/v1
DESCRIPTION:
StatefulSet represents a set of pods with consistent identities. Identities
are defined as: - Network: A single stable DNS and hostname. - Storage: As
many VolumeClaims as requested. The StatefulSet guarantees that a given
network identity will always map to the same storage identity.
FIELDS:
apiVersion
kind
metadata
如上所述,一个完整的 StatefulSet 控制器由一个 Headless Service、一个 StatefulSet 和一个 volumeClaimTemplate 组成。如下资源清单中的定义:
vim app.yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: myapp-sts
spec:
serviceName: sts-svc
replicas: 3
selector:
matchLabels:
app: myapp-sts
template:
metadata:
labels:
app: myapp-sts
spec:
containers:
- name: myapp
image: soscscs/myapp:v1
ports:
- containerPort: 80
name: web
volumeMounts:
- name: www
mountPath: /usr/share/nginx/html
volumeClaimTemplates:
- metadata:
name: www
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: "nfs-client-storageclass"
resources:
requests:
storage: 2Gi
kubectl apply -f app.yaml
kubectl get pod
报错:pod创建出现了Pending
#查看创建的过程
kubectl describe pod myapp-0
#出现以下此错误
Events:
Type Reason Age From Message
Warning FailedScheduling 7m8s default-scheduler 0/3 nodes are available: 3 pod has unbound immediate PersistentVolumeClaims.
Warning FailedScheduling 7m8s default-scheduler 0/3 nodes are available: 3 pod has unbound immediate PersistentVolumeClaims.解决报错方案:
#由于 1.20 版本启用了 selfLink,所以 k8s 1.20+ 版本通过 nfs provisioner 动态生成pv会报错,解决方法如下:
vim /etc/kubernetes/manifests/kube-apiserver.yaml
spec:
containers:
- command:
- kube-apiserver
- –feature-gates=RemoveSelfLink=false #添加这一行注意复制进去格式和配置文件格式一样需要前面添加一个(-)
- –advertise-address=192.168.198.11
————————————————#查看
kubectl get pod -n kube-system
或
kubectl get pod -n kube-system|grep apiserver#重新创建并查看
kubectl apply -f /etc/kubernetes/manifests/kube-apiserver.yaml
kubectl get pod -n kube-system|grep apiserver#查看
kubectl delete pods kube-apiserver -n kube-system
kubectl get pods -n kube-system | grep apiserver
解析上例:由于 StatefulSet 资源依赖于一个实现存在的 Headless 类型的 Service 资源,所以需要先定义一个名为 myapp-svc 的 Headless Service 资源,用于为关联到每个 Pod 资源创建 DNS 资源记录。接着定义了一个名为 myapp 的 StatefulSet 资源,它通过 Pod 模板创建了 3 个 Pod 资源副本,并基于 volumeClaimTemplates 向前面创建的PV进行了请求大小为 2Gi 的专用存储卷。
stor01节点操作
mkdir -p /data/volumes/v{1,2,3,4,5}
vim /etc/exports
/data/volumes/v1 192.168.198.0/24(rw,no_root_squash)
/data/volumes/v2 192.168.198.0/24(rw,no_root_squash)
/data/volumes/v3 192.168.198.0/24(rw,no_root_squash)
/data/volumes/v4 192.168.198.0/24(rw,no_root_squash)
/data/volumes/v5 192.168.198.0/24(rw,no_root_squash)
#检测有没有安装nfs,如没有安装nfs请先安装
rpm -q rpcbind nfs-utils
systemctl restart rpcbind
systemctl restart nfs
exportfs -arv
showmount -e
node节点操作
vim /etc/hosts
192.168.198.14 stor01
master节点操作
vim pv-demo.yaml
apiVersion: v1
kind: PersistentVolume
metadata:
name: pv001
labels:
name: pv001
spec:
nfs:
path: /data/volumes/v1
server: stor01
accessModes: ["ReadWriteMany","ReadWriteOnce"]
capacity:
storage: 1Gi
---
apiVersion: v1
kind: PersistentVolume
metadata:
name: pv002
labels:
name: pv002
spec:
nfs:
path: /data/volumes/v2
server: stor01
accessModes: ["ReadWriteOnce"]
capacity:
storage: 2Gi
---
apiVersion: v1
kind: PersistentVolume
metadata:
name: pv003
labels:
name: pv003
spec:
nfs:
path: /data/volumes/v3
server: stor01
accessModes: ["ReadWriteMany","ReadWriteOnce"]
capacity:
storage: 2Gi
---
apiVersion: v1
kind: PersistentVolume
metadata:
name: pv004
labels:
name: pv004
spec:
nfs:
path: /data/volumes/v4
server: stor01
accessModes: ["ReadWriteMany","ReadWriteOnce"]
capacity:
storage: 2Gi
---
apiVersion: v1
kind: PersistentVolume
metadata:
name: pv005
labels:
name: pv005
spec:
nfs:
path: /data/volumes/v5
server: stor01
accessModes: ["ReadWriteMany","ReadWriteOnce"]
capacity:
storage: 2Gi
kubectl apply -f pv-demo.yaml
kubectl get pv
vim pod-vol-pvc.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: mypvc
namespace: default
spec:
accessModes: ["ReadWriteMany"]
resources:
requests:
storage: 2Gi
---
apiVersion: v1
kind: Pod
metadata:
name: pod-vol-pvc
namespace: default
spec:
containers:
- name: myapp
image: ikubernetes/myapp:v1
volumeMounts:
- name: html
mountPath: /usr/share/nginx/html
volumes:
- name: html
persistentVolumeClaim:
claimName: mypvc
kubectl apply -f pod-vol-pvc.yaml
kubectl get pv
kubectl get pvc
vim stateful-demo.yaml
apiVersion: v1
kind: Service
metadata:
name: myapp-svc
labels:
app: myapp-svc
spec:
ports:
- port: 80
name: web
clusterIP: None
selector:
app: myapp-pod
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: myapp
spec:
serviceName: myapp-svc
replicas: 3
selector:
matchLabels:
app: myapp-pod
template:
metadata:
labels:
app: myapp-pod
spec:
containers:
- name: myapp
image: ikubernetes/myapp:v1
ports:
- containerPort: 80
name: web
volumeMounts:
- name: myappdata
mountPath: /usr/share/nginx/html
volumeClaimTemplates:
- metadata:
name: myappdata
annotations: #动态PV创建时,使用annotations在PVC里声明一个StorageClass对象的标识进行关联
volume.beta.kubernetes.io/storage-class: nfs-client-storageclass
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 2Gi
kubectl apply -f stateful-demo.yaml
#查看创建的无头服务myapp-svc
kubectl get svc
#查看statefulset
kubectl get sts
NAME DESIRED CURRENT AGE
myapp 3 3 55s
#查看pvc绑定
kubectl get pvc
NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE
myappdata-myapp-0 Bound pv002 2Gi RWO 1m
myappdata-myapp-1 Bound pv003 2Gi RWO,RWX 1m
myappdata-myapp-2 Bound pv004 2Gi RWO,RWX 1m
#查看pv绑定
kubectl get pv
NAME CAPACITY ACCESS MODES RECLAIM POLICY STATUS CLAIM STORAGECLASS REASON AGE
pv001 1Gi RWO,RWX Retain Available 6m
pv002 2Gi RWO Retain Bound default/myappdata-myapp-0 6m
pv003 2Gi RWO,RWX Retain Bound default/myappdata-myapp-1 6m
pv004 2Gi RWO,RWX Retain Bound default/myappdata-myapp-2 6m
pv005 2Gi RWO,RWX Retain Available 6m
#查看Pod信息
kubectl get pods
NAME READY STATUS RESTARTS AGE
myapp-0 1/1 Running 0 2m
myapp-1 1/1 Running 0 2m
myapp-2 1/1 Running 0 2m
kubectl delete -f stateful-demo.yaml
#当删除的时候是从myapp-2开始进行删除的,关闭是逆向关闭
kubectl get pods -w
#此时PVC依旧存在的,再重新创建pod时,依旧会重新去绑定原来的pvc
kubectl apply -f stateful-demo.yaml
kubectl get pvc
NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE
myappdata-myapp-0 Bound pv002 2Gi RWO 5m
myappdata-myapp-1 Bound pv003 2Gi RWO,RWX 5m
myappdata-myapp-2 Bound pv004 2Gi RWO,RWX
StatefulSet 控制器将在 StatefulSet 中删除并重新创建每个 Pod。它将以与 Pod 终止相同的顺序进行(从最大的序数到最小的序数),每次更新一个 Pod。在更新其前身之前,它将等待正在更新的 Pod 状态变成正在运行并就绪。如下操作的滚动更新是按照2-0的顺序更新。
#修改image版本为v2
vim stateful-demo.yaml
image: ikubernetes/myapp:v2
kubectl apply -f stateful-demo.yaml
#查看滚动更新的过程
kubectl get pods -w
NAME READY STATUS RESTARTS AGE
myapp-0 1/1 Running 0 29s
myapp-1 1/1 Running 0 27s
myapp-2 0/1 Terminating 0 26s
myapp-2 0/1 Terminating 0 30s
myapp-2 0/1 Terminating 0 30s
myapp-2 0/1 Pending 0 0s
myapp-2 0/1 Pending 0 0s
myapp-2 0/1 ContainerCreating 0 0s
myapp-2 1/1 Running 0 31s
myapp-1 1/1 Terminating 0 62s
myapp-1 0/1 Terminating 0 63s
myapp-1 0/1 Terminating 0 66s
myapp-1 0/1 Terminating 0 67s
myapp-1 0/1 Pending 0 0s
myapp-1 0/1 Pending 0 0s
myapp-1 0/1 ContainerCreating 0 0s
myapp-1 1/1 Running 0 30s
myapp-0 1/1 Terminating 0 99s
myapp-0 0/1 Terminating 0 100s
myapp-0 0/1 Terminating 0 101s
myapp-0 0/1 Terminating 0 101s
myapp-0 0/1 Pending 0 0s
myapp-0 0/1 Pending 0 0s
myapp-0 0/1 ContainerCreating 0 0s
myapp-0 1/1 Running 0 1s
在创建的每一个Pod中,每一个pod自己的名称都是可以被解析的
kubectl exec -it myapp-0 /bin/sh
Name: myapp-0.myapp-svc.default.svc.cluster.local
Address 1: 10.244.2.27 myapp-0.myapp-svc.default.svc.cluster.local
/ # nslookup myapp-1.myapp-svc.default.svc.cluster.local
nslookup: can’t resolve ‘(null)’: Name does not resolve
Name: myapp-1.myapp-svc.default.svc.cluster.local
Address 1: 10.244.1.14 myapp-1.myapp-svc.default.svc.cluster.local
/ # nslookup myapp-2.myapp-svc.default.svc.cluster.local
nslookup: can’t resolve ‘(null)’: Name does not resolve
Name: myapp-2.myapp-svc.default.svc.cluster.local
Address 1: 10.244.2.26 myapp-2.myapp-svc.default.svc.cluster.local
从上面的解析,我们可以看到在容器当中可以通过对Pod的名称进行解析到ip。其解析的域名格式如下:
(pod_name).(service_name).(namespace_name).svc.cluster.local
vim pod6.yaml
apiVersion: v1
kind: Pod
metadata:
name: dns-test
spec:
containers:
- name: busybox
image: busybox:1.28.4
args:
- /bin/sh
- -c
- sleep 36000
restartPolicy: Never
vim sts.yaml
apiVersion: v1
kind: Service
metadata:
name: nginx
labels:
app: nginx
spec:
ports:
- port: 80
name: web
selector:
app: nginx
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: nginx-statefulset
spec:
serviceName: nginx
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:latest
ports:
- containerPort: 80
kubectl apply -f sts.yaml
kubectl apply -f pod6.yaml
kubectl get pods,svc
kubectl exec -it dns-test sh
/ # nslookup nginx-statefulset-0.nginx.default.svc.cluster.local
/ # nslookup nginx-statefulset-1.nginx.default.svc.cluster.local
/ # nslookup nginx-statefulset-2.nginx.default.svc.cluster.local
#可以使用以下查看解析的信息
vim /etc/resolv.conf
exit
kubectl exec -it nginx-statefulset-0 bash
/# curl nginx-statefulset-0.nginx
/# curl nginx-statefulset-1.nginx
/# curl nginx-statefulset-2.nginx
exit
![v!v](https://img-blog.csdnimg.cn/2edcd91e282c4452aeba428933221ff3.png)
kubectl scale sts nginx-statefulset --replicas=4 #扩容副本增加到4个,默认值就是一个
kubectl get pods -w #动态查看扩容
kubectl get pv #查看pv绑定
kubectl patch sts nginx-statefulset -p '{"spec":{"replicas":2}}' #打补丁方式缩容
kubectl get pods -w #动态查看缩容
ELK,zabbix,普罗米修斯监控,数据变动可用这个控制器,数据库暴露可以用这个暴露
(1)DaemonSet 确保全部(或者一些)Node 上运行一个 Pod 的副本。当有 Node 加入集群时,也会为他们新增一个 Pod 。当有 Node 从集群移除时,这些 Pod 也会被回收。删除 DaemonSet 将会删除它创建的所有 Pod。
(2)使用 DaemonSet 的一些典型用法:
●运行集群存储 daemon,例如在每个 Node 上运行 glusterd、ceph。
●在每个 Node 上运行日志收集 daemon,例如fluentd、logstash。
●在每个 Node 上运行监控 daemon,例如 Prometheus Node Exporter、collectd、Datadog 代理、New Relic 代理,或 Ganglia gmond。
应用场景:Agent
//官方案例(监控)
https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/
vim ds.yaml
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: nginx-daemonset
labels:
app: nginx
spec:
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.15.4
ports:
- containerPort: 80
kubectl apply -f ds.yaml
#DaemonSet会在每个node节点都创建一个Pod
kubectl get pods
nginx-daemonset-2kcfd 1/1 Running 0 90s
nginx-daemonset-gcqvp 1/1 Running 0 90s
常用于运行那些仅需要执行一次的任务
应用场景:数据库迁移、批处理脚本、kube-bench扫描、离线数据处理,视频解码等业务
https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/
vim job.yaml
apiVersion: batch/v1
kind: Job
metadata:
name: pi
spec:
template:
spec:
containers:
- name: pi
image: perl
command: ["perl", "-Mbignum=bpi", "-wle", "print bpi(2000)"]
restartPolicy: Never
backoffLimit: 4
参数解释
.spec.template.spec.restartPolicy该属性拥有三个候选值:OnFailure,Never和Always。默认值为Always。它主要用于描述Pod内容器的重启策略。在Job中只能将此属性设置为OnFailure或Never,否则Job将不间断运行。.spec.backoffLimit用于设置job失败后进行重试的次数,默认值为6。默认情况下,除非Pod失败或容器异常退出,Job任务将不间断的重试,此时Job遵循 .spec.backoffLimit上述说明。一旦.spec.backoffLimit达到,作业将被标记为失败。
#在所有node节点下载perl镜像,因为镜像比较大,所以建议提前下载好
docker pull perl
kubectl apply -f job.yaml
kubectl get pods
pi-zqljx 1/1 Running 0 7s
#结果输出到控制台
kubectl logs pi-zqljx
3.14159265......
#清除job资源
kubectl delete -f job.yaml
#backoffLimit
vim job-limit.yaml
apiVersion: batch/v1
kind: Job
metadata:
name: busybox
spec:
template:
spec:
containers:
- name: busybox
image: busybox
imagePullPolicy: IfNotPresent
command: ["/bin/sh", "-c", "sleep 10;date;exit 1"]
restartPolicy: Never
backoffLimit: 2
kubectl apply -f job-limit.yaml
kubectl get job,pods
kubectl describe job busybox
......
Warning BackoffLimitExceeded 43s job-controller Job has reached the specified backoff limit
周期性任务,像Linux的Crontab一样。
周期性任务
应用场景:通知,备份
https://kubernetes.io/docs/tasks/job/automated-tasks-with-cron-jobs/
#每分钟打印hello
vim cronjob.yaml
apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: hello
spec:
schedule: "*/1 * * * *"
jobTemplate:
spec:
template:
spec:
containers:
- name: hello
image: busybox
imagePullPolicy: IfNotPresent
args:
- /bin/sh
- -c
- date; echo Hello from the Kubernetes cluster
restartPolicy: OnFailure
cronjob其它可用参数的配置
spec:
concurrencyPolicy: Allow #要保留的失败的完成作业数(默认为1)
schedule: ‘*/1 * * * *’ #作业时间表。在此示例中,作业将每分钟运行一次
startingDeadlineSeconds: 15 #pod必须在规定时间后的15秒内开始执行,若超过该时间未执行,则任务将不运行,且标记失败
successfulJobsHistoryLimit: 3 #要保留的成功完成的作业数(默认为3)
terminationGracePeriodSeconds: 30 #job存活时间 默认不设置为永久
jobTemplate: #作业模板。这类似于工作示例
kubectl create -f cronjob.yaml
kubectl get cronjob
NAME SCHEDULE SUSPEND ACTIVE LAST SCHEDULE AGE
hello */1 * * * * False 1 14s 42s
kubectl get pods
NAME READY STATUS RESTARTS AGE
hello-1695712200-dvhvg 0/1 Completed 0 2m4s
hello-1695712260-qmg9f 0/1 Completed 0 64s
hello-1695712320-9q54t 0/1 Completed 0 4s
kubectl logs hello-1695712200-dvhvg
Tue Sep 26 07:10:08 UTC 2023
Hello from the Kubernetes cluster
//如果报错:Error from server (Forbidden): Forbidden (user=system:anonymous, verb=get, resource=nodes, subresource=proxy) ( pods/log hello-1621587780-c7v54)
//解决办法:绑定一个cluster-admin的权限
kubectl create clusterrolebinding system:anonymous --clusterrole=cluster-admin --user=system:anonymous
pod控制器是用于管理一组pod的运行状态,pod控制器可以确保pod以一定的数量和副本数运行,并能够处理不同pod启动和终止的情况。pod控制器还可以通过升级pod的镜像版本来实现应用程序的更新和扩展。
①部署无状态应用的,管理RelicaSet(RS)和pod创建pod,维护pod副本的数目与期望值相同
②创建和删除pod是并行执行的,升级时是先创建一部分再删除一部分
①部署有状态的应用的
每个pod的唯一且变得,且每个pod拥有自己专属的持久化存储(基于PVC和PV)
K8S集群内部可以通过,还可以通过(pod_name).(service_name).(namespace_name).svc .cluster.local解析出pod的IP(基于headless service 和 coreDNS)
②创建和删除pod是有序的(串行运行的)
①理论上可以在K8S集群的所有node节点上创建相同的pod(不论node节点什么时候加入到K8S集群),但是会受到node节点上的污点影响(有污点就不会在节点上)
①部署一次性任务的pod,正藏完成之后容器立即退出并不会重启容器(restarPolicy不设置Always),也不会重建pod,异常完成后会重建pod重试任务,重建次数根据backofflimit配置指定(默认6次)
①周期性的部署任务的pod,正常完成后容器立即退出不会重启容器(restarPolicy不设置Always),也不会重建pod,scheduler 配置周期性的时间表。