Kubernetes 中常用模板
Pod 基础属性模板
apiVersion: v1
kind: Pod
metadata:
name: test
namespace: liangxiao
annotations:
user: "liangxiao"
labels:
app: centos
spec:
activeDeadlineSeconds: 6000 # 逾期设置,如果超过这个时间6000秒,Pod 会被退出,并设置DeadlineExceeded状态,并且不会重新拉起
dnsPolicy: ClusterFirst
hostAliases: # 设置pod 中 /etc/hosts 文件内容
- ip: "8.8.8.8"
hostnames:
- "www.google.com"
- "www.google.cn"
imagePullSecrets: # 指定镜像拉取的密钥凭据
- name: centos
hostIPC: true # 设定Pod 与 宿主之间的共享进程通信
restartPolicy: Always # 设定Pod 的重启策略
hostname: centos
# hostNetwork: true # 设定Pod 与 宿主之间的网络命名空间共享;注意:hostNetwork 不可以和 hostname 共存
hostPID: true
initContainers:
- name: init
image: centos:7
command: ["/bin/bash"]
args: ["-c","echo hello world > /workdir/index.html"]
volumeMounts:
- name: workdir
mountPath: "/workdir"
containers:
- name: centos
image: 'centos:7'
imagePullPolicy: Always
volumeMounts:
- name: workdir
mountPath: "/usr/share/nginx/html"
command: ["/bin/bash"]
args: ["-c","while true; do echo ok ; sleep 10 ; done"]
readinessProbe:
exec:
command:
- ls
- /home
initialDelaySeconds: 3
timeoutSeconds: 1
terminationGracePeriodSeconds: 120 # 设定优雅退出时间;
volumes:
- name: workdir
emptyDir: {}
Deployment 基础属性模板
apiVersion: apps/v1
kind: Deployment
metadata:
name: centos
namespace: liangxiao
annotations:
user: liangxiao
labels:
app: centos
spec:
minReadySeconds: 10 # 最小就绪准备时间,即Pod 就绪探针就绪之后,还需要等10秒才能正常使用,默认是0秒。
replicas: 2 # 副本数2
revisionHistoryLimit: 2 # 允许保留的 rs 副本数,默认是10个;这里的保留rs 副本数不包含deployment目前正在关联的rs
selector: # 标签匹配选择
matchLabels:
app: demo
strategy: # 指定 deployment 升级更新Pod 的策略;分 Recreate 与 RollingUpdate
# type: Recreate # 如果是 rollingUpdate 则是滚动更新,如果是Recreate 则直接将之前的Pod 全部删除,重新新建Pod
type: RollingUpdate
rollingUpdate:
maxUnavailable: 30% # 最大不可用Pod 的比例
maxSurge: 30% # 最大滚动更新的比例,用来指定可以创建的超出 期望 Pod 个数的 Pod 数量。此值可以是绝对数(例如,5)或所需 Pods 的百分比(例如,10%)
template:
metadata:
annotations: # template 中做 注解使用的比较少。
user: liangxiao
labels:
app: demo
spec:
affinity: # 亲和调度策略
nodeAffinity: # node 亲和
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 1
preference:
matchExpressions:
- key: disk-type
operator: In
values:
- ssd
dnsConfig: # 配置/etc/resolv.conf 内容
nameservers:
- 223.5.5.5
- 8.8.8.8
searches:
- cluster.local
dnsPolicy: ClusterFirst # dnsConfig 可以与 dnsPolicy 同时配置; dnsPolicy 的优先级比 dnsConfig 的配置高
enableServiceLinks: false # 禁止环境变量的方式自动做注入,默认是开启的
hostAliases: # 配置 /etc/hosts 内容
- ip: "1.1.1.1"
hostnames:
- "test.aaa.com"
- "test.bbb.com"
hostIPC: true # 设定Pod 与 宿主之间的共享进程通信
restartPolicy: Always # 设定Pod 的重启策略
hostname: centos
terminationGracePeriodSeconds: 120 # 设定优雅退出时间
# hostNetwork: true # 设定Pod 与 宿主之间的网络命名空间共享;注意:hostNetwork 不可以和 hostname 共存
hostPID: true # 共享宿主与 容器的 Pid
restartPolicy: Always # 重启策略
tolerations: # 添加容忍
- key: "key1"
operator: "Exists"
effect: "NoSchedule"
initContainers: # 设定初始化容器
- name: init
image: centos:7
command: ["/bin/bash"]
args: ["-c","echo hello world > /workdir/index.html"]
volumeMounts:
- name: workdir
mountPath: "/workdir"
securityContext: # 设定安全上下文权限
runAsUser: 1000
runAsGroup: 3000
fsGroup: 2000
containers:
- name: centos
image: "centos:7"
imagePullPolicy: IfNotPresent
command: ["/bin/bash", "-c", "sleep 99999999"]
volumeMounts:
- name: workdir
mountPath: "/usr/share/nginx/html"
volumes:
- name: workdir
emptyDir: {}
CronJob 基础属性模板
apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: centos
namespace: default
spec:
concurrencyPolicy: Replace # 设置 cronjob 的并发运行策略,分Allow(允许)、Forbid(不允许)、Replace(如果新任务的执行时间到了而老任务没有执行完,CronJob 会用新任务替换当前正在运行的任务)
failedJobsHistoryLimit: 3 # 设置保留的失败的任务Pod 数量
successfulJobsHistoryLimit: 3 # 设置成功运行的Pod 保留数量
suspend: false # 挂起设置
schedule: '*/1 * * * *' # 调度时间策略,表示每分钟执行一次这个cronjob
jobTemplate: # cronjob 运行的 Pod 模板
spec:
activeDeadlineSeconds: 60 # 设置 Pod 运行时长,超过这个时长,Pod 中的任务程序未执行完毕,会被认定为是失败的任务
backoffLimit: 6 # 设置 Pod 运行失败重试次数
completions: 6 # 设置要 运行多少个 Pod任务数
parallelism: 6 # 设置并发运行的 Pod 数量
template:
spec:
containers:
- command:
- sleep
- "10"
image: centos:7
imagePullPolicy: IfNotPresent
name: centos
resources:
requests:
cpu: 250m
memory: 512Mi
dnsPolicy: ClusterFirst
restartPolicy: Never # 设置 Pod 的重启策略
schedulerName: default-scheduler
securityContext: {}
terminationGracePeriodSeconds: 30
Daemonsets 基础属性模板
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: nginx
labels:
app: web
spec:
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
tolerations:
- key: node.kubernetes.io/unschedulable
operator: Exists
effect: NoSchedule
containers:
- name: nginx
image: nginx:latest
resources:
limits:
memory: 200Mi
requests:
cpu: 100m
memory: 200Mi
volumeMounts:
- name: log
mountPath: /var/log/nginx/
readOnly: false
terminationGracePeriodSeconds: 30
volumes:
- name: log
hostPath:
path: /var/log
Job 基础属性模板
apiVersion: batch/v1
kind: Job
metadata:
name: centos
namespace: default
spec:
activeDeadlineSeconds: 60 # 最大存活时间60秒
backoffLimit: 3 # Pod 运行异常的重试次数
completions: 4 # 最大运行测试的Pod 数量
parallelism: 2 # 同时运行的Pod 数量
template:
metadata:
labels:
job-name: centos
spec:
containers:
- command:
- sleep
- "10"
image: centos:7
imagePullPolicy: IfNotPresent
name: centos
resources:
limits:
cpu: "1"
memory: 512Mi
requests:
cpu: 500m
memory: 256Mi
dnsPolicy: ClusterFirst
restartPolicy: Never
schedulerName: default-scheduler
securityContext: {}
terminationGracePeriodSeconds: 30
Statefulsets 基础属性模板
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: web
spec:
selector:
matchLabels:
app: nginx
serviceName: "nginx"
replicas: 3
template:
metadata:
labels:
app: nginx
spec:
terminationGracePeriodSeconds: 10
containers:
- name: nginx
image: nginx:latest
ports:
- containerPort: 80
name: web
volumeMounts:
- name: www
mountPath: /usr/share/nginx/html
volumeClaimTemplates:
- metadata:
name: www
spec:
accessModes: [ "ReadWriteOnce" ]
storageClassName: "nas"
resources:
requests:
storage: 20Gi
Services 基础属性模板
apiVersion: v1
kind: Service
metadata:
name: web-1
namespace: default
spec:
clusterIP: 192.168.217.26 # 指定 cluster svc 的 IP 地址。这个地址必须是集群中svc 可被允许申请的地址段,并且IP 未被占用
ports:
- name: nginx
port: 80 # svc 转发的端口
protocol: TCP # svc 转发的协议
targetPort: 80 # Pod 程序的端口
selector: # svc 的标签选择器
app: nginx
sessionAffinity: None # svc 的tcp 四层会话保持设置。默认是 None,表示不做会话保持,一直轮询;如果设置为ClientIP ,即表示做会话保持。
type: ClusterIP # 指定 svc 的 服务类型为 ClusterIP 默认,还有NodePort、Loadbalancer、ExternalName
---
apiVersion: v1
kind: Service
metadata:
name: web-2
namespace: default
spec:
clusterIP: None # 设置svc 为 headless,即无头服务。无头服务是 ClusterIP 中的另一种表现形式
ports:
- name: nginx
port: 80
protocol: TCP
targetPort: 80
selector:
app: nginx
sessionAffinity: None
type: ClusterIP
---
apiVersion: v1
kind: Service
metadata:
name: web-3
namespace: default
spec:
clusterIP: 192.168.161.27
externalTrafficPolicy: Local # 设定流量转发策略为 local,对应的流量策略还有 Cluster
ports:
- name: nginx
nodePort: 30080
port: 80
protocol: TCP
targetPort: 80
selector:
app: nginx
sessionAffinity: None
type: NodePort # 设置 svc 为 nodeport 模式
---
apiVersion: v1
kind: Service
metadata:
name: web-4
namespace: default
spec:
clusterIP: 192.168.136.122
externalTrafficPolicy: Cluster
ports:
- name: nginx
nodePort: 32503
port: 80
protocol: TCP
targetPort: 80
selector:
app: nginx
sessionAffinity: None
type: LoadBalancer # loadbalancer 类型的svc,仅限云厂支持的组件功能模式
Ingress 基础属性模板
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: nginx
spec:
defaultBackend: # 指定默认匹配的 svc;默认匹配的 svc 只要请求转发到ingress,在其他的的 rules 未匹配的情况下,就会匹配defaultBackend
service:
name: nginx
port:
number: 80
rules: # 同一个 rule 做多个 host 的匹配
- host: "www.xunyan.com"
http:
paths:
- pathType: Prefix # 匹配类型;分Prefix 和 Exact 、 ImplementationSpecific;分别代表根号符断层匹配、精准匹配、自定义匹配规则
path: "/" # 匹配路径
backend: # 转发的后端信息
service: # 指定后端是个 svc
name: nginx # 指定具体转发的 svc
port: # 指定具体的端口
number: 80
- host: "*.xunyan.com"
http:
paths:
- pathType: Prefix
path: "/aaa"
backend:
service:
name: nginx
port:
number: 80
rules: # 同一个域名,不同的URL 做 svc 的转发
- host: www.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: tomcat
port:
number: 8080
- path: /index.html
pathType: Prefix
backend:
service:
name: httpd
port:
number: 80
- http: # 无请求标头(host)时,就请求这个。这个的优先级比 defaultbackend 高
paths:
- pathType: Prefix
path: "/"
backend:
service:
name: nginx-2
port:
number: 80
Configmap 基础属性模板
apiVersion: v1
kind: ConfigMap
metadata:
name: test-1
namespace: default
data:
path: /var/log
---
apiVersion: v1
kind: ConfigMap
metadata:
name: test-2
namespace: default
data:
level: INFO
---
apiVersion: v1
kind: Pod
metadata:
name: configmap-pod
spec:
containers:
- name: test
image: centos:7
command: ["/bin/bash", "-c", "sleep 99999"]
volumeMounts:
- name: logpath
mountPath: /etc/config-1 # 一个mountPath 对应一个 volumes,不可以一对多。
- name: loglevel
mountPath: /etc/config-2
volumes:
- name: logpath
configMap:
name: test-1
items:
- key: path
path: logpath
- name: loglevel
configMap:
name: test-2
items:
- key: level
path: loglevel
downwardAPI 基础属性模板
apiVersion: v1
kind: Pod
metadata:
name: test-1
labels:
app: test
annotations:
env: test
spec:
containers:
- name: centos
image: 'centos:7'
command: ["bash", "-c"]
args: ["sleep 9999999999999"]
volumeMounts:
- name: podinfo
mountPath: /etc/podinfo
volumes: # 通过卷的方式为Pod 或者 container 传递downwardAPI 参数
- name: podinfo
downwardAPI:
items: # 指定具体的items
- path: "labels"
fieldRef:
fieldPath: metadata.labels
- path: "annotations"
fieldRef:
fieldPath: metadata.annotations
---
apiVersion: v1
kind: Pod
metadata:
name: test-2
spec:
containers:
- name: centos
image: 'centos:7'
command: [ "bash", "-c"]
args: ["sleep 9999999999999999"]
env: # 通过env 的方式为Pod 或者 containers 传递downwardAPI参数
- name: MY_NODE_NAME
valueFrom:
fieldRef:
fieldPath: spec.nodeName
- name: MY_POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: MY_POD_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
- name: MY_POD_IP
valueFrom:
fieldRef:
fieldPath: status.podIP
- name: MY_POD_SERVICE_ACCOUNT
valueFrom:
fieldRef:
fieldPath: spec.serviceAccountName
restartPolicy: Never
empty 基础属性模板
apiVersion: v1
kind: Pod
metadata:
name: test
spec:
containers:
- name: centos
image: 'centos:7'
imagePullPolicy: Always
command: ["/bin/bash","-c","while true; do echo ok; sleep 1000 ; done"]
volumeMounts:
- mountPath: /disk
name: disk-volume
volumes:
- name: disk-volume
emptyDir: {} # 选择{} 空目录的方式挂载Pod 目录,emptyDir 的声明周期和Pod 就一样,Pod在emptyDir就在,目录数据内容也不会丢失
---
apiVersion: v1
kind: Pod
metadata:
name: test
spec:
containers:
- name: centos
image: 'centos:7'
imagePullPolicy: Always
command: ["/bin/bash","-c","while true; do echo ok; sleep 1000 ; done"]
volumeMounts:
- mountPath: /disk
name: disk-volume
volumes:
- name: disk-volume
emptyDir:
medium: Memory # 选择Memory 空目录的方式挂载Pod 目录,emptyDir 的声明周期和Pod 也是一样,Pod在emptyDir就在,但是Pod 或者 节点重启就会导致数据消失
hostPath 基础属性模板
apiVersion: v1
kind: Pod
metadata:
name: test
spec:
containers:
- image: "centos:7"
name: test
imagePullPolicy: Always
command: ["/bin/bash"]
args: ["-c","sleep 99999999"]
volumeMounts:
- mountPath: /host-data
name: test-volume
volumes:
- name: test-volume
hostPath:
path: /data # 宿主机中必须有这个路径才行
type: DirectoryOrCreate # 如果在给定路径上什么都不存在,那么将根据需要创建空目录,权限设置为 0755,具有与 kubelet 相同的组和属主信息;类似的参数还有:Directory、FileOrCreate、File、Socket、CharDevice、BlockDevice;具体详情可以参考官方文档:https://kubernetes.io/zh/docs/concepts/storage/volumes/#hostpath
projected 基础属性模板
kind: StorageClass
apiVersion: storage.k8s.io/v1
metadata:
name: local-sc # 创建对应的storageclass,否则pv 创建的时候没办法调用驱动进行绑定
provisioner: kubernetes.io/no-provisioner # 驱动提供者及类型
volumeBindingMode: WaitForFirstConsumer # 表示PV不要立即绑定PVC,而是直到有Pod需要用PVC的时候才绑定
---
apiVersion: v1
kind: PersistentVolume
metadata:
name: local-pv
spec:
capacity:
storage: 5Gi
accessModes:
- ReadWriteOnce
persistentVolumeReclaimPolicy: Retain
storageClassName: local-sc
local:
path: /opt # 这个路径必须在宿主机上面先创建,local 的本质其实就是 pathhost 加 nodeAffinity
nodeAffinity: # 指定要匹配的节点
required:
nodeSelectorTerms:
- matchExpressions:
- key: aaa
operator: In
values:
- bbb
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: local-pvc
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 5Gi
storageClassName: local-sc
---
kind: Pod
apiVersion: v1
metadata:
name: test
spec:
containers:
- name: nginx
image: nginx
volumeMounts:
- mountPath: "/usr/share/nginx/html"
name: local
volumes:
- name: local
persistentVolumeClaim:
claimName: local-pvc
# 原理说明参考文档:https://www.jianshu.com/p/d35fba102643
secrets 基础属性模板
apiVersion: v1
kind: Secret
metadata:
name: mysecret
type: Opaque # Opaque 表示自定义类型数据,其他类型的数据请参考:https://kubernetes.io/zh/docs/concepts/configuration/secret/#secret-types
data:
username: 25fb2fd3
password: bbbbbbbb
---
apiVersion: v1
kind: Pod
metadata:
name: test
spec:
containers:
- name: test
image: "centos:7"
imagePullPolicy: Always
volumeMounts:
- name: secrets
mountPath: "/etc/foo"
command: ["/bin/bash"]
args: ["-c","sleep 1000000"]
volumes:
- name: secrets
secret:
secretName: mysecret
subPath 基础属性模板
apiVersion: v1
kind: PersistentVolume
metadata:
name: pv-nas
spec:
accessModes: # 访问模式; ReadWriteOnce、ReadOnlyMany、ReadWriteMany
- ReadWriteMany
capacity: # 设定PV 容量的大小
storage: 20Gi
csi: # 指定驱动内容及存储介质
driver: nasplugin.csi.alibabacloud.com
volumeAttributes:
path: ''
server: 3539d493d3-eqm86.cn-shanghai.nas.aliyuncs.com
vers: '3'
volumeHandle: pv-nas # 唯一标识卷的字符串值。必须设置的参数,一般与metadata.name 匹配即可
persistentVolumeReclaimPolicy: Retain # 设定保留策略; Retain(保留)、Recycled(回收,已废弃)或 Deleted(删除)
volumeMode: Filesystem # 指定卷模式,分Filesystem(文件系统) 和 Block(块);Filesystem 的卷会被 Pod 挂载(Mount) 到某个目录。 如果卷的存储来自某块设备而该设备目前为空,Kuberneretes 会在第一次挂载卷之前 在设备上创建文件系统。
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: pvc-nas
namespace: default
spec:
accessModes: # 指定pv 的访问模式,和pvc 的保持对齐
- ReadWriteMany
resources: # 指定pv 资源的大小
requests:
storage: 20Gi
selector: # 指定要绑定匹配的 pv
matchLabels:
alicloud-pvname: pv-nas
volumeMode: Filesystem # 指定卷模式
volumeName: pv-nas
---
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: centos
name: centos
namespace: default
spec:
replicas: 2
selector:
matchLabels:
app: centos
template:
metadata:
labels:
app: centos
spec:
containers:
- command:
- sleep
- '999999999999999'
image: 'centos:7'
imagePullPolicy: IfNotPresent
name: centos
volumeMounts:
- mountPath: /data/test1
name: volume-pvc-nas
subPath: test1 # 可用于指定所引用的卷内的子路径,而不是其根路径
- mountPath: /data/test2
name: volume-pvc-nas
subPath: test2
dnsPolicy: ClusterFirst
restartPolicy: Always
volumes:
- name: volume-pvc-nas
persistentVolumeClaim:
claimName: pvc-nas
心若向阳,无谓悲伤!