当前位置: 首页 > news >正文

【Kubernets】Kubernetes 资源类型大全:使用场景与配置示例

Kubernetes 资源类型大全:使用场景与配置示例

  • Kubernetes 资源类型大全:使用场景与配置示例
    • 一、核心资源类型概览
    • 二、工作负载资源(Workload Resources)
      • 1. Pod
      • 2. Deployment
      • 3. StatefulSet
      • 4. DaemonSet
      • 5. Job
      • 6. CronJob
      • 7. ReplicaSet
    • 三、服务发现与负载均衡资源
      • 1. Service
      • 2. Ingress
      • 3. Endpoints/EndpointSlice
    • 四、配置资源
      • 1. ConfigMap
      • 2. Secret
    • 五、存储资源
      • 1. PersistentVolume (PV)
      • 2. PersistentVolumeClaim (PVC)
      • 3. StorageClass
    • 六、安全资源
      • 1. ServiceAccount
      • 2. Role / ClusterRole
      • 3. RoleBinding / ClusterRoleBinding
    • 七、集群资源
      • 1. Namespace
      • 2. ResourceQuota
      • 3. LimitRange
    • 八、扩展资源
      • 1. HorizontalPodAutoscaler (HPA)
      • 2. VerticalPodAutoscaler (VPA)
      • 3. NetworkPolicy
    • 九、自定义资源 (Custom Resources)
      • 1. CustomResourceDefinition (CRD)
      • 2. 自定义资源实例
    • 十、其他重要资源
      • 1. PodDisruptionBudget
      • 2. PriorityClass
      • 3. RuntimeClass
    • 十一、资源类型速查表
    • 十二、最佳实践总结

Kubernetes 资源类型大全:使用场景与配置示例

一、核心资源类型概览

Kubernetes资源
工作负载资源
服务发现资源
配置资源
存储资源
安全资源
集群资源
扩展资源
Pod
Deployment
StatefulSet
DaemonSet
Job/CronJob
ReplicaSet
Service
Ingress
Endpoint
ConfigMap
Secret
ResourceQuota
PersistentVolume
PersistentVolumeClaim
StorageClass
ServiceAccount
Role/RoleBinding
ClusterRole/ClusterRoleBinding
Namespace
Node
CustomResourceDefinition
HorizontalPodAutoscaler
VerticalPodAutoscaler
NetworkPolicy

二、工作负载资源(Workload Resources)

1. Pod

使用场景:最小部署单元,单容器或多容器应用

# pod-example.yaml
apiVersion: v1
kind: Pod
metadata:name: nginx-podlabels:app: nginx
spec:containers:- name: nginximage: nginx:1.21ports:- containerPort: 80env:- name: ENV_VARvalue: "production"resources:requests:memory: "64Mi"cpu: "250m"limits:memory: "128Mi"cpu: "500m"# 多容器示例- name: log-collectorimage: busyboxcommand: ['sh', '-c', 'tail -f /dev/null']

2. Deployment

使用场景:无状态应用部署,支持滚动更新、回滚

# deployment-example.yaml
apiVersion: apps/v1
kind: Deployment
metadata:name: web-applabels:app: web
spec:replicas: 3selector:matchLabels:app: webstrategy:type: RollingUpdaterollingUpdate:maxSurge: 25%maxUnavailable: 25%template:metadata:labels:app: webspec:containers:- name: webimage: nginx:1.21ports:- containerPort: 80livenessProbe:httpGet:path: /port: 80initialDelaySeconds: 30periodSeconds: 10readinessProbe:httpGet:path: /port: 80initialDelaySeconds: 5periodSeconds: 5resources:requests:cpu: 100mmemory: 128Milimits:cpu: 500mmemory: 512Mi

3. StatefulSet

使用场景:有状态应用,需要稳定网络标识、持久化存储

# statefulset-example.yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:name: mysql
spec:serviceName: "mysql"replicas: 3selector:matchLabels:app: mysqltemplate:metadata:labels:app: mysqlspec:containers:- name: mysqlimage: mysql:8.0ports:- containerPort: 3306env:- name: MYSQL_ROOT_PASSWORDvalueFrom:secretKeyRef:name: mysql-secretkey: passwordvolumeMounts:- name: mysql-datamountPath: /var/lib/mysqlvolumeClaimTemplates:- metadata:name: mysql-dataspec:accessModes: [ "ReadWriteOnce" ]storageClassName: "fast-ssd"resources:requests:storage: 20Gi

4. DaemonSet

使用场景:每个节点运行一个副本(日志收集、节点监控)

# daemonset-example.yaml
apiVersion: apps/v1
kind: DaemonSet
metadata:name: fluentd-logginglabels:k8s-app: fluentd-logging
spec:selector:matchLabels:name: fluentd-loggingtemplate:metadata:labels:name: fluentd-loggingspec:tolerations:- key: node-role.kubernetes.io/mastereffect: NoSchedulecontainers:- name: fluentdimage: fluent/fluentd:v1.14resources:limits:memory: 200Mirequests:cpu: 100mmemory: 200MivolumeMounts:- name: varlogmountPath: /var/log- name: varlibdockercontainersmountPath: /var/lib/docker/containersreadOnly: trueterminationGracePeriodSeconds: 30volumes:- name: varloghostPath:path: /var/log- name: varlibdockercontainershostPath:path: /var/lib/docker/containers

5. Job

使用场景:一次性任务、批处理作业

# job-example.yaml
apiVersion: batch/v1
kind: Job
metadata:name: pi-calculation
spec:completions: 5     # 需要完成5个Podparallelism: 2     # 同时运行2个PodbackoffLimit: 4    # 重试次数template:spec:containers:- name: piimage: perl:5.34command: ["perl",  "-Mbignum=bpi", "-wle", "print bpi(2000)"]restartPolicy: Never

6. CronJob

使用场景:定时任务、周期性作业

# cronjob-example.yaml
apiVersion: batch/v1
kind: CronJob
metadata:name: database-backup
spec:schedule: "0 2 * * *"  # 每天凌晨2点startingDeadlineSeconds: 200concurrencyPolicy: Forbid  # 禁止并发执行jobTemplate:spec:template:spec:containers:- name: backupimage: postgres:13command:- /bin/sh- -c- pg_dump -h db-host -U postgres mydb > /backup/backup.sqlenv:- name: PGPASSWORDvalueFrom:secretKeyRef:name: postgres-secretkey: passwordvolumeMounts:- name: backup-volumemountPath: /backupvolumes:- name: backup-volumepersistentVolumeClaim:claimName: backup-pvcrestartPolicy: OnFailure

7. ReplicaSet

使用场景:Pod副本管理(Deployment底层使用)

# replicaset-example.yaml
apiVersion: apps/v1
kind: ReplicaSet
metadata:name: frontendlabels:app: guestbooktier: frontend
spec:replicas: 3selector:matchLabels:tier: frontendtemplate:metadata:labels:tier: frontendspec:containers:- name: php-redisimage: gcr.io/google_samples/gb-frontend:v3resources:requests:cpu: 100mmemory: 100Mienv:- name: GET_HOSTS_FROMvalue: dnsports:- containerPort: 80

三、服务发现与负载均衡资源

1. Service

使用场景:服务发现、负载均衡、网络访问抽象

# service-example.yaml
apiVersion: v1
kind: Service
metadata:name: web-service
spec:selector:app: webports:- name: httpport: 80targetPort: 8080protocol: TCP- name: httpsport: 443targetPort: 8443protocol: TCPtype: LoadBalancer  # ClusterIP, NodePort, LoadBalancer# 外部负载均衡器配置externalTrafficPolicy: LocalloadBalancerIP: 192.168.1.100

2. Ingress

使用场景:HTTP/HTTPS路由、域名基于的路由、SSL终止

# ingress-example.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:name: example-ingressannotations:nginx.ingress.kubernetes.io/rewrite-target: /cert-manager.io/cluster-issuer: "letsencrypt-prod"
spec:tls:- hosts:- app.example.comsecretName: example-tlsrules:- host: app.example.comhttp:paths:- path: /pathType: Prefixbackend:service:name: web-serviceport:number: 80- path: /apipathType: Prefixbackend:service:name: api-serviceport:number: 8080

3. Endpoints/EndpointSlice

使用场景:手动配置服务端点

# endpoints-example.yaml
apiVersion: v1
kind: Endpoints
metadata:name: external-service
subsets:
- addresses:- ip: 192.168.1.100- ip: 192.168.1.101ports:- port: 80name: http

四、配置资源

1. ConfigMap

使用场景:配置数据存储、环境变量、配置文件

# configmap-example.yaml
apiVersion: v1
kind: ConfigMap
metadata:name: app-config
data:# 简单键值对log-level: "info"database-url: "postgresql://localhost:5432/mydb"# 配置文件nginx.conf: |server {listen 80;server_name localhost;location / {proxy_pass http://backend;}}# 属性文件application.properties: |server.port=8080spring.datasource.url=jdbc:mysql://localhost:3306/mydb

2. Secret

使用场景:敏感信息存储(密码、令牌、密钥)

# secret-example.yaml
apiVersion: v1
kind: Secret
metadata:name: app-secrets
type: Opaque
data:# Base64编码的数据username: YWRtaW4=password: cGFzc3dvcmQxMjM=database-url: cG9zdGdyZXNxbDovL3VzZXI6cGFzc0BkYjoxMjM0L2RibmFtZQ==# 使用TLS Secret
apiVersion: v1
kind: Secret
metadata:name: tls-secret
type: kubernetes.io/tls
data:tls.crt: <base64编码的证书>tls.key: <base64编码的私钥>

五、存储资源

1. PersistentVolume (PV)

使用场景:集群范围的存储资源

# persistentvolume-example.yaml
apiVersion: v1
kind: PersistentVolume
metadata:name: pv-volumelabels:type: local
spec:capacity:storage: 10GiaccessModes:- ReadWriteOncepersistentVolumeReclaimPolicy: RetainstorageClassName: slowhostPath:path: "/mnt/data"

2. PersistentVolumeClaim (PVC)

使用场景:用户对存储的请求

# persistentvolumeclaim-example.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:name: pv-claim
spec:storageClassName: slowaccessModes:- ReadWriteOnceresources:requests:storage: 3Gi

3. StorageClass

使用场景:动态卷配置、存储类别定义

# storageclass-example.yaml
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:name: fast-ssd
provisioner: kubernetes.io/gce-pd
parameters:type: pd-ssdreplication-type: none
allowVolumeExpansion: true
mountOptions:- discard

六、安全资源

1. ServiceAccount

使用场景:Pod身份认证、API访问控制

# serviceaccount-example.yaml
apiVersion: v1
kind: ServiceAccount
metadata:name: build-robotnamespace: default
secrets:
- name: build-robot-token-xyz

2. Role / ClusterRole

使用场景:命名空间/集群范围的权限定义

# role-example.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:namespace: defaultname: pod-reader
rules:
- apiGroups: [""]resources: ["pods"]verbs: ["get", "watch", "list"]# clusterrole-example.yaml  
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:name: cluster-admin
rules:
- apiGroups: [""]resources: ["*"]verbs: ["*"]
- apiGroups: ["*"]resources: ["*"]verbs: ["*"]

3. RoleBinding / ClusterRoleBinding

使用场景:角色绑定到主体

# rolebinding-example.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:name: read-podsnamespace: default
subjects:
- kind: Username: janeapiGroup: rbac.authorization.k8s.io
roleRef:kind: Rolename: pod-readerapiGroup: rbac.authorization.k8s.io

七、集群资源

1. Namespace

使用场景:资源隔离、多租户环境

# namespace-example.yaml
apiVersion: v1
kind: Namespace
metadata:name: productionlabels:name: productionenvironment: prod

2. ResourceQuota

使用场景:资源配额限制

# resourcequota-example.yaml
apiVersion: v1
kind: ResourceQuota
metadata:name: compute-resourcesnamespace: production
spec:hard:requests.cpu: "1"requests.memory: 1Gilimits.cpu: "2"limits.memory: 2Girequests.storage: 10Gipersistentvolumeclaims: "4"services.loadbalancers: "2"services.nodeports: "0"

3. LimitRange

使用场景:限制资源请求和限制的默认值

# limitrange-example.yaml
apiVersion: v1
kind: LimitRange
metadata:name: mem-limit-rangenamespace: production
spec:limits:- default:memory: 512Micpu: 500mdefaultRequest:memory: 256Micpu: 100mtype: Container

八、扩展资源

1. HorizontalPodAutoscaler (HPA)

使用场景:基于CPU/内存使用率自动扩缩容

# hpa-example.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:name: web-app-hpa
spec:scaleTargetRef:apiVersion: apps/v1kind: Deploymentname: web-appminReplicas: 2maxReplicas: 10metrics:- type: Resourceresource:name: cputarget:type: UtilizationaverageUtilization: 50- type: Resourceresource:name: memorytarget:type: UtilizationaverageUtilization: 80behavior:scaleDown:stabilizationWindowSeconds: 300policies:- type: Percentvalue: 50periodSeconds: 60

2. VerticalPodAutoscaler (VPA)

使用场景:自动调整Pod资源请求

# vpa-example.yaml
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:name: web-app-vpa
spec:targetRef:apiVersion: "apps/v1"kind: Deploymentname: web-appupdatePolicy:updateMode: "Auto"resourcePolicy:containerPolicies:- containerName: "*"minAllowed:cpu: 100mmemory: 50MimaxAllowed:cpu: 1memory: 1GicontrolledResources: ["cpu", "memory"]

3. NetworkPolicy

使用场景:Pod网络策略、网络安全控制

# networkpolicy-example.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:name: api-allow-frontendnamespace: production
spec:podSelector:matchLabels:app: apipolicyTypes:- Ingressingress:- from:- podSelector:matchLabels:app: frontend- namespaceSelector:matchLabels:name: monitoringports:- protocol: TCPport: 8080

九、自定义资源 (Custom Resources)

1. CustomResourceDefinition (CRD)

使用场景:扩展Kubernetes API

# crd-example.yaml
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:name: databases.example.com
spec:group: example.comversions:- name: v1served: truestorage: trueschema:openAPIV3Schema:type: objectproperties:spec:type: objectproperties:databaseName:type: stringversion:type: stringreplicas:type: integerscope: Namespacednames:plural: databasessingular: databasekind: DatabaseshortNames:- db

2. 自定义资源实例

# custom-resource-example.yaml
apiVersion: "example.com/v1"
kind: Database
metadata:name: my-postgres-db
spec:databaseName: "production-db"version: "13.2"replicas: 3

十、其他重要资源

1. PodDisruptionBudget

使用场景:维护应用可用性,优雅驱逐Pod

# pdb-example.yaml
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:name: web-pdb
spec:minAvailable: 2  # 或 maxUnavailable: 1selector:matchLabels:app: web

2. PriorityClass

使用场景:Pod调度优先级

# priorityclass-example.yaml
apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata:name: high-priority
value: 1000000
globalDefault: false
description: "用于关键业务Pod"

3. RuntimeClass

使用场景:选择容器运行时

# runtimeclass-example.yaml
apiVersion: node.k8s.io/v1
kind: RuntimeClass
metadata:name: gvisor
handler: runsc  # 容器运行时处理器

十一、资源类型速查表

资源类型API版本主要用途使用场景
Podv1最小部署单元单容器/多容器应用
Deploymentapps/v1无状态应用部署Web服务、API服务
StatefulSetapps/v1有状态应用数据库、消息队列
DaemonSetapps/v1节点级别部署日志收集、监控代理
Jobbatch/v1一次性任务数据处理、批处理
CronJobbatch/v1定时任务备份、报表生成
Servicev1服务发现负载均衡、服务暴露
Ingressnetworking.k8s.io/v1HTTP路由域名路由、SSL终止
ConfigMapv1配置管理应用配置、环境变量
Secretv1敏感信息密码、密钥、令牌
PersistentVolumev1存储资源持久化存储
PersistentVolumeClaimv1存储请求动态存储分配
ServiceAccountv1身份认证Pod API访问
Role/RoleBindingrbac.authorization.k8s.io/v1权限控制命名空间权限
Namespacev1资源隔离多租户环境
ResourceQuotav1资源限制配额管理
HPAautoscaling/v2自动扩缩容基于指标自动调整
NetworkPolicynetworking.k8s.io/v1网络策略网络安全控制

十二、最佳实践总结

  1. 工作负载选择

    • 无状态应用:使用 Deployment
    • 有状态应用:使用 StatefulSet
    • 节点级别服务:使用 DaemonSet
    • 批处理任务:使用 Job/CronJob
  2. 存储策略

    • 临时数据:使用 emptyDir
    • 持久化数据:使用 PVC + StorageClass
    • 敏感配置:使用 Secret
    • 普通配置:使用 ConfigMap
  3. 安全实践

    • 最小权限原则:使用 RBAC
    • 网络隔离:使用 NetworkPolicy
    • 资源限制:使用 ResourceQuota + LimitRange
  4. 高可用性

    • 多副本部署:使用 HPA 自动扩缩容
    • 优雅终止:使用 PDB 保证可用性
    • 健康检查:配置 liveness/readiness probes

通过合理组合这些资源类型,可以构建出生产级可用的 Kubernetes 应用架构。

http://www.dtcms.com/a/558275.html

相关文章:

  • 成都哪里做网站如何做像京东淘宝那样的网站
  • 有没有建筑学做区位分析的网站淘宝联盟合作网站api
  • 《守正传艺:谷晟阳奇门遁甲教学的真实实践路径》
  • 网上家教网站开发网站首页原型图咋做
  • 数据结构==优先级队列与堆==
  • ⸢ 拾壹 ⸥⤳ 威胁感知与响应应用的实践案例
  • 在哪个网站上做实验仪器比较好深圳网站建设卓企
  • 基于n8n实现数据库多表数据同步
  • 网站服务器租广州各区最新动态
  • 做百度网站的公司哪家好开发软件的成本预算
  • linux基础服务使用流程
  • 提供设计网站效果图seo 网站文章一般要多少字
  • `pytest + YAML + Allure` 的接口自动化测试框架是业界广泛使用的组合
  • 做网站 需求怎么写wordpress 数据库连接字符串
  • webkitx(Android WebView 最佳实践库)--> 上
  • 怎么把文件发送到网站荣耀手机的商城在哪
  • 论文阅读:Multi-Spectral Image Color Reproduction
  • 怎样做元古建筑的网站结构图asp做素材网站
  • MongoDB Java:深入解析与应用实践
  • 有服务器和网站代码了 怎么建站ifm网站做啥的
  • Pikachu-国产轻量化 Web 漏洞靶场
  • 网站的域名每年都要续费手帐风格wordpress主题
  • 深入洞察:大模型推理能力及MindIE引擎
  • 番禺做网站哪家专业ppt怎么制作流程图
  • 多模态生成 Flamingo
  • Linux文件上传下载
  • 网站资料如何做脚注wordpress 注册 登录界面
  • 网站dns修改wordpress 该插件没有有效的标题
  • 2025年大湾区杯粤港澳金融数模竞赛B题完整数据集分享
  • 深圳市做网站知名公司有哪些创业平台是干什么的