Kubernetes核心知识详解
·
Kubernetes 核心知识详解
本文档详细讲解 K8s 的访问方式、配置语法、所有组件和配置项
目录
一、网络访问详解
1.1 K8s 网络模型
┌─────────────────────────────────────────────────────────────────────────────────┐
│ K8s 网络层次 │
├─────────────────────────────────────────────────────────────────────────────────┤
│ │
│ 第1层:Pod 网络 │
│ ───────────────────────────────────────────────────────────────── │
│ • 每个 Pod 有独立 IP(如 172.16.0.100) │
│ • Pod 内容器共享网络(localhost 互通) │
│ • Pod 之间可以直接通过 IP 通信 │
│ • ⚠️ Pod IP 不固定,重启会变 │
│ │
│ 第2层:Service 网络 │
│ ───────────────────────────────────────────────────────────────── │
│ • Service 有固定 ClusterIP(如 10.96.0.100) │
│ • 通过 Service 名访问(如 backend-service) │
│ • 自动负载均衡到后端 Pod │
│ • ⚠️ ClusterIP 只能集群内访问 │
│ │
│ 第3层:Ingress / 外部访问 │
│ ───────────────────────────────────────────────────────────────── │
│ • Ingress:HTTP/HTTPS 入口 │
│ • LoadBalancer:云厂商负载均衡 │
│ • NodePort:节点端口暴露 │
│ │
└─────────────────────────────────────────────────────────────────────────────────┘
1.2 内部访问(集群内 Pod 互访)
方式1:通过 Service 名访问(推荐)
┌─────────────────────────────────────────────────────────────────────────────────┐
│ 通过 Service 名访问 │
├─────────────────────────────────────────────────────────────────────────────────┤
│ │
│ 完整格式: │
│ http://<service-name>.<namespace>.svc.cluster.local:<port> │
│ │
│ 简写格式(同命名空间内): │
│ http://<service-name>:<port> │
│ │
│ ════════════════════════════════════════════════════════════════════════════ │
│ 举例 │
│ ════════════════════════════════════════════════════════════════════════════ │
│ │
│ 假设: │
│ • Service 名:backend-service │
│ • 命名空间:prod │
│ • 端口:8080 │
│ │
│ ┌────────────────────────────────────────────────────────────────────────┐ │
│ │ 完整写法(跨命名空间也能用): │ │
│ │ http://backend-service.prod.svc.cluster.local:8080 │ │
│ │ │ │
│ │ 简写1(同命名空间内): │ │
│ │ http://backend-service.prod:8080 │ │
│ │ │ │
│ │ 简写2(同命名空间内,最短): │ │
│ │ http://backend-service:8080 │ │
│ └────────────────────────────────────────────────────────────────────────┘ │
│ │
│ ════════════════════════════════════════════════════════════════════════════ │
│ 在代码中使用 │
│ ════════════════════════════════════════════════════════════════════════════ │
│ │
│ Spring Boot application.yml: │
│ ┌────────────────────────────────────────────────────────────────────────┐ │
│ │ spring: │ │
│ │ datasource: │ │
│ │ url: jdbc:mysql://mysql-service:3306/mydb │ │
│ │ redis: │ │
│ │ host: redis-service │ │
│ │ port: 6379 │ │
│ └────────────────────────────────────────────────────────────────────────┘ │
│ │
│ 访问其他微服务: │
│ ┌────────────────────────────────────────────────────────────────────────┐ │
│ │ // 同命名空间 │ │
│ │ String url = "http://user-service:8080/api/users"; │ │
│ │ │ │
│ │ // 跨命名空间(访问 common 命名空间的服务) │ │
│ │ String url = "http://auth-service.common:8080/api/auth"; │ │
│ └────────────────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────────────┘
方式2:通过环境变量访问
# K8s 自动为每个 Service 注入环境变量
# 格式:<SERVICE_NAME>_SERVICE_HOST 和 <SERVICE_NAME>_SERVICE_PORT
# 例如 Service 名为 backend-service,会自动生成:
# BACKEND_SERVICE_SERVICE_HOST=10.96.0.100
# BACKEND_SERVICE_SERVICE_PORT=8080
# 在 Pod 中使用:
env:
- name: BACKEND_URL
value: "http://$(BACKEND_SERVICE_SERVICE_HOST):$(BACKEND_SERVICE_SERVICE_PORT)"
1.3 外部访问(从集群外访问)
┌─────────────────────────────────────────────────────────────────────────────────┐
│ 外部访问方式对比 │
├─────────────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌───────────────┬─────────────┬──────────────────┬──────────────────────────┐ │
│ │ 方式 │ 适用场景 │ 原理 │ 示例 │ │
│ ├───────────────┼─────────────┼──────────────────┼──────────────────────────┤ │
│ │ ClusterIP │ 只能内部访问 │ 虚拟IP,仅集群内 │ 后端服务 │ │
│ │ (默认) │ │ │ │ │
│ ├───────────────┼─────────────┼──────────────────┼──────────────────────────┤ │
│ │ NodePort │ 测试/简单场景│ 在节点开放端口 │ 节点IP:30080 │ │
│ │ │ │ 30000-32767 │ │ │
│ ├───────────────┼─────────────┼──────────────────┼──────────────────────────┤ │
│ │ LoadBalancer │ 云环境 │ 云厂商创建LB │ 有独立公网IP │ │
│ │ │ │ 自动分配公网IP │ 费用较高 │ │
│ ├───────────────┼─────────────┼──────────────────┼──────────────────────────┤ │
│ │ Ingress │ 生产环境 │ HTTP/HTTPS入口 │ 多服务共享一个入口 │ │
│ │ (推荐) │ 多服务 │ 路由分发 │ 支持域名、证书 │ │
│ └───────────────┴─────────────┴──────────────────┴──────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────────────┘
方式1:NodePort
# ═══════════════════════════════════════════════════════════════════════════════
# NodePort Service
# 作用:在每个节点上开放一个端口,外部可以通过 节点IP:NodePort 访问
# ═══════════════════════════════════════════════════════════════════════════════
apiVersion: v1
kind: Service
metadata:
name: backend-service
namespace: prod
spec:
type: NodePort # 【关键】类型设为 NodePort
selector:
app: backend
ports:
- port: 8080 # Service 端口(集群内访问用)
targetPort: 8080 # Pod 端口
nodePort: 30080 # 节点端口(外部访问用)
# nodePort 范围:30000-32767
# 不指定会自动分配
# 访问方式:
# http://<任意节点IP>:30080
# http://10.0.1.20:30080
# http://10.0.1.21:30080
# http://10.0.1.22:30080
方式2:LoadBalancer
# ═══════════════════════════════════════════════════════════════════════════════
# LoadBalancer Service
# 作用:云厂商自动创建负载均衡器,分配公网IP
# ═══════════════════════════════════════════════════════════════════════════════
apiVersion: v1
kind: Service
metadata:
name: backend-service
namespace: prod
annotations:
# 阿里云 SLB 配置
service.beta.kubernetes.io/alibaba-cloud-loadbalancer-address-type: "internet"
# internet = 公网,intranet = 内网
spec:
type: LoadBalancer # 【关键】类型设为 LoadBalancer
selector:
app: backend
ports:
- port: 80 # 对外端口
targetPort: 8080 # Pod 端口
# 创建后查看分配的公网IP:
# kubectl get svc backend-service -n prod
# EXTERNAL-IP 列就是公网IP
# 访问方式:
# http://<EXTERNAL-IP>:80
方式3:Ingress(推荐!)
# ═══════════════════════════════════════════════════════════════════════════════
# Ingress
# 作用:HTTP/HTTPS 入口网关,支持路由分发、域名、证书
# 优点:多个服务共享一个入口,节省成本
# ═══════════════════════════════════════════════════════════════════════════════
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: app-ingress
namespace: prod
annotations:
kubernetes.io/ingress.class: nginx
spec:
rules:
- host: example.com # 域名
http:
paths:
- path: / # 路径
pathType: Prefix
backend:
service:
name: frontend-service
port:
number: 80
- path: /api # /api 开头的请求
pathType: Prefix
backend:
service:
name: backend-service
port:
number: 8080
# 访问方式:
# http://example.com → frontend-service
# http://example.com/api → backend-service
1.4 访问方式总结图
┌─────────────────────────────────────────────────────────────────────────────────┐
│ K8s 访问方式全景图 │
├─────────────────────────────────────────────────────────────────────────────────┤
│ │
│ 外部用户 │
│ │ │
│ │ https://example.com │
│ ▼ │
│ ┌───────────────────────────────────────────────────────────────────────┐ │
│ │ Ingress Controller │ │
│ │ (处理 HTTPS、路由) │ │
│ └───────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ │ 路由分发 │
│ ├──────────────────────────────────────────┐ │
│ ▼ ▼ │
│ ┌─────────────────────────┐ ┌─────────────────────────┐ │
│ │ Service: frontend │ │ Service: backend │ │
│ │ type: ClusterIP │ │ type: ClusterIP │ │
│ │ ClusterIP: 10.96.0.10 │ │ ClusterIP: 10.96.0.20 │ │
│ └─────────────────────────┘ └─────────────────────────┘ │
│ │ │ │
│ │ 负载均衡 │ 负载均衡 │
│ ├─────────┬─────────┐ ├─────────┬─────────┐ │
│ ▼ ▼ ▼ ▼ ▼ ▼ │
│ ┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐ │
│ │ Pod 1 │ │ Pod 2 │ │ Pod 3 │ │ Pod 1 │ │ Pod 2 │ │ Pod 3 │ │
│ │ 前端 │ │ 前端 │ │ 前端 │ │ 后端 │ │ 后端 │ │ 后端 │ │
│ └───────┘ └───────┘ └───────┘ └───────┘ └───────┘ └───────┘ │
│ │ │ │
│ │ 内部访问 │ │
│ │ http://frontend-service:80 │ │
│ └──────────────────────────────────────────┘ │
│ │ │
│ │ 访问数据库 │
│ ▼ │
│ ┌─────────────────────────┐ │
│ │ Service: mysql │ │
│ │ mysql-service:3306 │ │
│ └─────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────────────┘
二、YAML配置语法详解
2.1 环境变量引用语法 $(VAR_NAME)
┌─────────────────────────────────────────────────────────────────────────────────┐
│ $(VAR_NAME) 语法详解 │
├─────────────────────────────────────────────────────────────────────────────────┤
│ │
│ 这是什么? │
│ ───────────────────────────────────────────────────────────────── │
│ • K8s 的环境变量引用语法 │
│ • 在 value 字段中引用其他已定义的环境变量 │
│ • 在 Pod 启动时,K8s 会把 $(VAR_NAME) 替换成实际值 │
│ │
│ 语法规则: │
│ ───────────────────────────────────────────────────────────────── │
│ • 格式:$(变量名) │
│ • 变量名:之前定义的 env.name │
│ • 只能在 value 字段中使用 │
│ • 引用的变量必须在前面定义 │
│ │
│ ════════════════════════════════════════════════════════════════════════════ │
│ 完整示例 │
│ ════════════════════════════════════════════════════════════════════════════ │
│ │
│ env: │
│ # 1. 先定义基础变量 │
│ - name: MYSQL_HOST │
│ value: "mysql-service" │
│ │
│ - name: MYSQL_PORT │
│ value: "3306" │
│ │
│ - name: MYSQL_DATABASE │
│ value: "mydb" │
│ │
│ # 2. 然后用 $() 引用组合 │
│ - name: SPRING_DATASOURCE_URL │
│ value: "jdbc:mysql://$(MYSQL_HOST):$(MYSQL_PORT)/$(MYSQL_DATABASE)" │
│ # 最终值:jdbc:mysql://mysql-service:3306/mydb │
│ │
│ ════════════════════════════════════════════════════════════════════════════ │
│ 执行流程 │
│ ════════════════════════════════════════════════════════════════════════════ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ YAML 文件中: │ │
│ │ value: "jdbc:mysql://$(MYSQL_HOST):$(MYSQL_PORT)/$(MYSQL_DATABASE)" │ │
│ │ │ │ │ │ │
│ │ ▼ ▼ ▼ │ │
│ │ K8s 替换后: │ │
│ │ value: "jdbc:mysql://mysql-service:3306/mydb" │ │
│ │ │ │
│ │ 容器中的环境变量: │ │
│ │ SPRING_DATASOURCE_URL=jdbc:mysql://mysql-service:3306/mydb │ │
│ └─────────────────────────────────────────────────────────────────────────┘ │
│ │
│ ════════════════════════════════════════════════════════════════════════════ │
│ 与 Shell 变量的区别 │
│ ════════════════════════════════════════════════════════════════════════════ │
│ │
│ ┌─────────────────┬────────────────────────────────────────────────────────┐│
│ │ 语法 │ 说明 ││
│ ├─────────────────┼────────────────────────────────────────────────────────┤│
│ │ $(VAR) │ K8s 语法,在 Pod 创建时替换 ││
│ │ ${VAR} │ Shell 语法,在容器运行时替换 ││
│ │ $VAR │ Shell 语法,在容器运行时替换 ││
│ └─────────────────┴────────────────────────────────────────────────────────┘│
│ │
│ 举例对比: │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ # K8s 语法 - Pod 启动前替换 │ │
│ │ command: ["echo", "$(MY_VAR)"] │ │
│ │ │ │
│ │ # Shell 语法 - 容器运行时替换 │ │
│ │ command: ["/bin/sh", "-c", "echo $MY_VAR"] │ │
│ │ command: ["/bin/sh", "-c", "echo ${MY_VAR}"] │ │
│ └─────────────────────────────────────────────────────────────────────────┘ │
│ │
│ ════════════════════════════════════════════════════════════════════════════ │
│ 转义 │
│ ════════════════════════════════════════════════════════════════════════════ │
│ │
│ 如果想输出字面量 $(VAR) 而不是替换,用 $$(VAR): │
│ value: "$$(MY_VAR)" # 最终值是字符串 "$(MY_VAR)" │
│ │
└─────────────────────────────────────────────────────────────────────────────────┘
2.2 其他引用语法
┌─────────────────────────────────────────────────────────────────────────────────┐
│ K8s 配置值的所有来源 │
├─────────────────────────────────────────────────────────────────────────────────┤
│ │
│ ════════════════════════════════════════════════════════════════════════════ │
│ 1. 直接写值 │
│ ════════════════════════════════════════════════════════════════════════════ │
│ │
│ env: │
│ - name: LOG_LEVEL │
│ value: "INFO" # 直接写字符串 │
│ │
│ ════════════════════════════════════════════════════════════════════════════ │
│ 2. 从 Secret 获取(敏感信息) │
│ ════════════════════════════════════════════════════════════════════════════ │
│ │
│ env: │
│ - name: DB_PASSWORD │
│ valueFrom: │
│ secretKeyRef: │
│ name: mysql-secret # Secret 资源的名称 │
│ key: password # Secret 中的 key │
│ optional: false # 是否可选,默认 false │
│ │
│ # 对应的 Secret: │
│ # apiVersion: v1 │
│ # kind: Secret │
│ # metadata: │
│ # name: mysql-secret │
│ # stringData: │
│ # password: "MyPassword123!" │
│ │
│ ════════════════════════════════════════════════════════════════════════════ │
│ 3. 从 ConfigMap 获取(配置信息) │
│ ════════════════════════════════════════════════════════════════════════════ │
│ │
│ env: │
│ - name: LOG_LEVEL │
│ valueFrom: │
│ configMapKeyRef: │
│ name: app-config # ConfigMap 资源的名称 │
│ key: log_level # ConfigMap 中的 key │
│ │
│ ════════════════════════════════════════════════════════════════════════════ │
│ 4. 从 Pod 信息获取(fieldRef) │
│ ════════════════════════════════════════════════════════════════════════════ │
│ │
│ env: │
│ - name: MY_POD_NAME │
│ valueFrom: │
│ fieldRef: │
│ fieldPath: metadata.name │
│ │
│ ┌─────────────────────────────┬────────────────────────────────────────────┐ │
│ │ fieldPath │ 获取的值 │ │
│ ├─────────────────────────────┼────────────────────────────────────────────┤ │
│ │ metadata.name │ Pod 名称 │ │
│ │ metadata.namespace │ 命名空间 │ │
│ │ metadata.uid │ Pod UID │ │
│ │ metadata.labels['key'] │ 标签值 │ │
│ │ metadata.annotations['key'] │ 注解值 │ │
│ │ spec.nodeName │ 节点名称 │ │
│ │ spec.serviceAccountName │ ServiceAccount 名称 │ │
│ │ status.podIP │ Pod IP 地址 │ │
│ │ status.hostIP │ 节点 IP 地址 │ │
│ └─────────────────────────────┴────────────────────────────────────────────┘ │
│ │
│ ════════════════════════════════════════════════════════════════════════════ │
│ 5. 从容器资源信息获取(resourceFieldRef) │
│ ════════════════════════════════════════════════════════════════════════════ │
│ │
│ env: │
│ - name: MY_CPU_LIMIT │
│ valueFrom: │
│ resourceFieldRef: │
│ containerName: backend │
│ resource: limits.cpu │
│ │
│ ┌─────────────────────────────┬────────────────────────────────────────────┐ │
│ │ resource │ 获取的值 │ │
│ ├─────────────────────────────┼────────────────────────────────────────────┤ │
│ │ limits.cpu │ CPU 限制值 │ │
│ │ limits.memory │ 内存限制值 │ │
│ │ requests.cpu │ CPU 请求值 │ │
│ │ requests.memory │ 内存请求值 │ │
│ └─────────────────────────────┴────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────────────┘
2.3 YAML 基本语法规则
┌─────────────────────────────────────────────────────────────────────────────────┐
│ K8s YAML 语法规则 │
├─────────────────────────────────────────────────────────────────────────────────┤
│ │
│ 1. 缩进规则 │
│ ───────────────────────────────────────────────────────────────── │
│ • 只能用空格,不能用 Tab │
│ • 通常用 2 个空格 │
│ • 缩进表示层级关系 │
│ │
│ 2. 数据类型 │
│ ───────────────────────────────────────────────────────────────── │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ # 字符串 │ │
│ │ name: backend # 不加引号 │ │
│ │ name: "backend" # 双引号 │ │
│ │ name: 'backend' # 单引号 │ │
│ │ name: "8080" # 数字字符串要加引号 │ │
│ │ │ │
│ │ # 数字 │ │
│ │ replicas: 3 # 整数 │ │
│ │ cpu: 0.5 # 浮点数 │ │
│ │ port: 8080 # 端口号 │ │
│ │ │ │
│ │ # 布尔值 │ │
│ │ enabled: true # 真 │ │
│ │ enabled: false # 假 │ │
│ │ enabled: "true" # ⚠️ 这是字符串,不是布尔值 │ │
│ │ │ │
│ │ # 空值 │ │
│ │ value: null │ │
│ │ value: ~ # 波浪号也表示 null │ │
│ │ │ │
│ │ # 列表(数组) │ │
│ │ ports: │ │
│ │ - 8080 │ │
│ │ - 9090 │ │
│ │ # 或者写成一行 │ │
│ │ ports: [8080, 9090] │ │
│ │ │ │
│ │ # 对象(映射) │ │
│ │ metadata: │ │
│ │ name: backend │ │
│ │ namespace: prod │ │
│ │ # 或者写成一行 │ │
│ │ metadata: {name: backend, namespace: prod} │ │
│ └─────────────────────────────────────────────────────────────────────────┘ │
│ │
│ 3. 多行字符串 │
│ ───────────────────────────────────────────────────────────────── │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ # | 保留换行符(Literal) │ │
│ │ command: | │ │
│ │ echo "line1" │ │
│ │ echo "line2" │ │
│ │ # 结果:"echo \"line1\"\necho \"line2\"\n" │ │
│ │ │ │
│ │ # > 折叠换行符(Folded),换行变空格 │ │
│ │ command: > │ │
│ │ echo "line1" │ │
│ │ echo "line2" │ │
│ │ # 结果:"echo \"line1\" echo \"line2\"\n" │ │
│ │ │ │
│ │ # |- 不保留末尾换行 │ │
│ │ # |+ 保留末尾所有换行 │ │
│ └─────────────────────────────────────────────────────────────────────────┘ │
│ │
│ 4. 注释 │
│ ───────────────────────────────────────────────────────────────── │
│ # 这是注释 │
│ name: backend # 行尾注释 │
│ │
│ 5. 多文档 │
│ ───────────────────────────────────────────────────────────────── │
│ --- 分隔多个文档 │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ apiVersion: v1 │ │
│ │ kind: Service │ │
│ │ ... │ │
│ │ --- # 分隔符 │ │
│ │ apiVersion: apps/v1 │ │
│ │ kind: Deployment │ │
│ │ ... │ │
│ └─────────────────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────────────┘
三、所有资源对象详解
3.1 资源对象分类
┌─────────────────────────────────────────────────────────────────────────────────┐
│ K8s 资源对象分类 │
├─────────────────────────────────────────────────────────────────────────────────┤
│ │
│ ════════════════════════════════════════════════════════════════════════════ │
│ 工作负载(Workload) │
│ ════════════════════════════════════════════════════════════════════════════ │
│ ┌────────────────┬──────────────────────────────────────────────────────────┐│
│ │ 资源 │ 用途 ││
│ ├────────────────┼──────────────────────────────────────────────────────────┤│
│ │ Pod │ 最小部署单元,包含容器 ││
│ │ Deployment │ 无状态应用(Web、API)【最常用】 ││
│ │ StatefulSet │ 有状态应用(数据库、消息队列) ││
│ │ DaemonSet │ 每个节点运行一个 Pod(日志收集、监控) ││
│ │ Job │ 一次性任务 ││
│ │ CronJob │ 定时任务 ││
│ │ ReplicaSet │ 管理 Pod 副本(由 Deployment 自动管理) ││
│ └────────────────┴──────────────────────────────────────────────────────────┘│
│ │
│ ════════════════════════════════════════════════════════════════════════════ │
│ 服务发现和负载均衡(Service Discovery) │
│ ════════════════════════════════════════════════════════════════════════════ │
│ ┌────────────────┬──────────────────────────────────────────────────────────┐│
│ │ 资源 │ 用途 ││
│ ├────────────────┼──────────────────────────────────────────────────────────┤│
│ │ Service │ 为 Pod 提供固定访问入口和负载均衡 ││
│ │ Endpoints │ Service 关联的 Pod IP 列表(自动管理) ││
│ │ Ingress │ HTTP/HTTPS 入口网关 ││
│ └────────────────┴──────────────────────────────────────────────────────────┘│
│ │
│ ════════════════════════════════════════════════════════════════════════════ │
│ 配置和存储(Configuration & Storage) │
│ ════════════════════════════════════════════════════════════════════════════ │
│ ┌────────────────┬──────────────────────────────────────────────────────────┐│
│ │ 资源 │ 用途 ││
│ ├────────────────┼──────────────────────────────────────────────────────────┤│
│ │ ConfigMap │ 存储非敏感配置 ││
│ │ Secret │ 存储敏感信息(密码、密钥) ││
│ │ PersistentVolume (PV) │ 持久化存储卷 ││
│ │ PersistentVolumeClaim (PVC)│ 存储卷声明 ││
│ │ StorageClass │ 存储类型定义 ││
│ └────────────────┴──────────────────────────────────────────────────────────┘│
│ │
│ ════════════════════════════════════════════════════════════════════════════ │
│ 集群管理(Cluster) │
│ ════════════════════════════════════════════════════════════════════════════ │
│ ┌────────────────┬──────────────────────────────────────────────────────────┐│
│ │ 资源 │ 用途 ││
│ ├────────────────┼──────────────────────────────────────────────────────────┤│
│ │ Namespace │ 命名空间(资源隔离) ││
│ │ Node │ 集群节点 ││
│ │ ResourceQuota │ 资源配额限制 ││
│ │ LimitRange │ 默认资源限制 ││
│ └────────────────┴──────────────────────────────────────────────────────────┘│
│ │
│ ════════════════════════════════════════════════════════════════════════════ │
│ 权限控制(RBAC) │
│ ════════════════════════════════════════════════════════════════════════════ │
│ ┌────────────────┬──────────────────────────────────────────────────────────┐│
│ │ 资源 │ 用途 ││
│ ├────────────────┼──────────────────────────────────────────────────────────┤│
│ │ ServiceAccount │ Pod 身份标识 ││
│ │ Role │ 命名空间内权限 ││
│ │ ClusterRole │ 集群级权限 ││
│ │ RoleBinding │ 绑定 Role 到用户/ServiceAccount ││
│ │ ClusterRoleBinding│ 绑定 ClusterRole ││
│ └────────────────┴──────────────────────────────────────────────────────────┘│
│ │
│ ════════════════════════════════════════════════════════════════════════════ │
│ 自动扩缩(Autoscaling) │
│ ════════════════════════════════════════════════════════════════════════════ │
│ ┌────────────────┬──────────────────────────────────────────────────────────┐│
│ │ 资源 │ 用途 ││
│ ├────────────────┼──────────────────────────────────────────────────────────┤│
│ │ HorizontalPodAutoscaler (HPA)│ 水平自动扩缩(根据 CPU/内存/自定义指标) ││
│ │ VerticalPodAutoscaler (VPA) │ 垂直自动扩缩(调整 requests/limits) ││
│ └────────────────┴──────────────────────────────────────────────────────────┘│
│ │
└─────────────────────────────────────────────────────────────────────────────────┘
3.2 每个资源的 apiVersion 和 kind
┌─────────────────────────────────────────────────────────────────────────────────┐
│ apiVersion 和 kind 速查表 │
├─────────────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌───────────────────────┬──────────────────────┬───────────────────────────┐ │
│ │ kind │ apiVersion │ 说明 │ │
│ ├───────────────────────┼──────────────────────┼───────────────────────────┤ │
│ │ Pod │ v1 │ 核心资源 │ │
│ │ Service │ v1 │ 核心资源 │ │
│ │ ConfigMap │ v1 │ 核心资源 │ │
│ │ Secret │ v1 │ 核心资源 │ │
│ │ Namespace │ v1 │ 核心资源 │ │
│ │ PersistentVolume │ v1 │ 核心资源 │ │
│ │ PersistentVolumeClaim │ v1 │ 核心资源 │ │
│ │ ServiceAccount │ v1 │ 核心资源 │ │
│ ├───────────────────────┼──────────────────────┼───────────────────────────┤ │
│ │ Deployment │ apps/v1 │ 应用资源 │ │
│ │ StatefulSet │ apps/v1 │ 应用资源 │ │
│ │ DaemonSet │ apps/v1 │ 应用资源 │ │
│ │ ReplicaSet │ apps/v1 │ 应用资源 │ │
│ ├───────────────────────┼──────────────────────┼───────────────────────────┤ │
│ │ Job │ batch/v1 │ 批处理资源 │ │
│ │ CronJob │ batch/v1 │ 批处理资源 │ │
│ ├───────────────────────┼──────────────────────┼───────────────────────────┤ │
│ │ Ingress │ networking.k8s.io/v1 │ 网络资源 │ │
│ │ NetworkPolicy │ networking.k8s.io/v1 │ 网络资源 │ │
│ ├───────────────────────┼──────────────────────┼───────────────────────────┤ │
│ │ Role │ rbac.authorization.k8s.io/v1│ RBAC 资源 │ │
│ │ ClusterRole │ rbac.authorization.k8s.io/v1│ RBAC 资源 │ │
│ │ RoleBinding │ rbac.authorization.k8s.io/v1│ RBAC 资源 │ │
│ │ ClusterRoleBinding │ rbac.authorization.k8s.io/v1│ RBAC 资源 │ │
│ ├───────────────────────┼──────────────────────┼───────────────────────────┤ │
│ │ HorizontalPodAutoscaler│ autoscaling/v2 │ 自动扩缩 │ │
│ ├───────────────────────┼──────────────────────┼───────────────────────────┤ │
│ │ StorageClass │ storage.k8s.io/v1 │ 存储资源 │ │
│ └───────────────────────┴──────────────────────┴───────────────────────────┘ │
│ │
│ 如何查找某个资源的 apiVersion? │
│ kubectl api-resources | grep Deployment │
│ │
└─────────────────────────────────────────────────────────────────────────────────┘
四、配置项完整清单
4.1 Deployment 完整配置项清单
# ═══════════════════════════════════════════════════════════════════════════════
# Deployment 所有配置项清单
# ═══════════════════════════════════════════════════════════════════════════════
apiVersion: apps/v1 # API 版本
kind: Deployment # 资源类型
metadata: # 元数据
name: xxx # 名称(必填)
namespace: xxx # 命名空间
labels: # 标签
key: value
annotations: # 注解
key: value
spec: # 规格
replicas: 3 # 副本数
selector: # 选择器(必填)
matchLabels: # 精确匹配
key: value
matchExpressions: # 表达式匹配
- key: xxx
operator: In/NotIn/Exists/DoesNotExist
values: [xxx]
strategy: # 更新策略
type: RollingUpdate/Recreate
rollingUpdate:
maxSurge: 1 # 最大超出数
maxUnavailable: 0 # 最大不可用数
minReadySeconds: 0 # 最小就绪时间
revisionHistoryLimit: 10 # 保留历史版本数
progressDeadlineSeconds: 600 # 部署超时时间
paused: false # 是否暂停
template: # Pod 模板
metadata:
labels:
key: value
annotations:
key: value
spec: # Pod 规格
# ═══════════ 容器配置 ═══════════
containers:
- name: xxx # 容器名
image: xxx # 镜像
imagePullPolicy: Always/IfNotPresent/Never
command: ["/bin/sh"] # 启动命令
args: ["-c", "xxx"] # 命令参数
workingDir: /app # 工作目录
ports:
- name: http
containerPort: 8080
protocol: TCP/UDP
hostPort: 8080 # 宿主机端口(不推荐)
env:
- name: XXX
value: "xxx"
- name: XXX
valueFrom:
secretKeyRef:
name: xxx
key: xxx
configMapKeyRef:
name: xxx
key: xxx
fieldRef:
fieldPath: metadata.name
resourceFieldRef:
resource: limits.cpu
envFrom: # 批量导入环境变量
- configMapRef:
name: xxx
- secretRef:
name: xxx
resources:
requests:
memory: "256Mi"
cpu: "250m"
limits:
memory: "512Mi"
cpu: "500m"
volumeMounts:
- name: xxx
mountPath: /data
subPath: xxx # 子路径
readOnly: false
livenessProbe: # 存活探针
httpGet:
path: /health
port: 8080
scheme: HTTP
httpHeaders:
- name: xxx
value: xxx
tcpSocket:
port: 8080
exec:
command: ["xxx"]
initialDelaySeconds: 30
periodSeconds: 10
timeoutSeconds: 5
successThreshold: 1
failureThreshold: 3
readinessProbe: # 就绪探针
# 同 livenessProbe
startupProbe: # 启动探针
# 同 livenessProbe
lifecycle:
postStart:
exec:
command: ["xxx"]
httpGet:
path: /xxx
port: 8080
preStop:
exec:
command: ["sleep", "15"]
securityContext: # 安全上下文
runAsUser: 1000
runAsGroup: 1000
runAsNonRoot: true
readOnlyRootFilesystem: true
allowPrivilegeEscalation: false
capabilities:
add: ["NET_ADMIN"]
drop: ["ALL"]
# ═══════════ Init 容器 ═══════════
initContainers:
- name: init
image: xxx
command: ["xxx"]
# ═══════════ 卷配置 ═══════════
volumes:
- name: xxx
emptyDir: {} # 临时目录
- name: xxx
hostPath: # 宿主机目录
path: /data
type: Directory/File/DirectoryOrCreate
- name: xxx
configMap: # ConfigMap
name: xxx
items:
- key: xxx
path: xxx
- name: xxx
secret: # Secret
secretName: xxx
- name: xxx
persistentVolumeClaim: # PVC
claimName: xxx
# ═══════════ 调度配置 ═══════════
nodeSelector: # 节点选择
key: value
nodeName: xxx # 指定节点
affinity:
nodeAffinity: # 节点亲和性
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: xxx
operator: In
values: [xxx]
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
preference:
matchExpressions:
- key: xxx
operator: In
values: [xxx]
podAffinity: # Pod 亲和性
# 同上
podAntiAffinity: # Pod 反亲和性
# 同上
tolerations: # 容忍污点
- key: "xxx"
operator: "Equal/Exists"
value: "xxx"
effect: "NoSchedule/PreferNoSchedule/NoExecute"
tolerationSeconds: 3600
# ═══════════ 其他配置 ═══════════
restartPolicy: Always/OnFailure/Never # 重启策略
terminationGracePeriodSeconds: 30 # 优雅终止时间
dnsPolicy: ClusterFirst/Default/None # DNS 策略
serviceAccountName: xxx # ServiceAccount
hostNetwork: false # 使用宿主机网络
hostPID: false # 使用宿主机 PID
hostname: xxx # 主机名
subdomain: xxx # 子域名
priorityClassName: xxx # 优先级类
imagePullSecrets: # 镜像拉取凭证
- name: xxx
securityContext: # Pod 安全上下文
runAsUser: 1000
runAsGroup: 1000
fsGroup: 1000
4.2 Service 完整配置项清单
# ═══════════════════════════════════════════════════════════════════════════════
# Service 所有配置项清单
# ═══════════════════════════════════════════════════════════════════════════════
apiVersion: v1
kind: Service
metadata:
name: xxx
namespace: xxx
labels:
key: value
annotations:
# 阿里云 SLB 配置
service.beta.kubernetes.io/alibaba-cloud-loadbalancer-address-type: "internet"
service.beta.kubernetes.io/alibaba-cloud-loadbalancer-spec: "slb.s1.small"
spec:
type: ClusterIP/NodePort/LoadBalancer/ExternalName
selector:
key: value
ports:
- name: http
port: 80 # Service 端口
targetPort: 8080 # Pod 端口
nodePort: 30080 # 节点端口(NodePort 类型)
protocol: TCP/UDP/SCTP
clusterIP: 10.96.0.100 # 指定 ClusterIP(可选)
# clusterIP: None # Headless Service
externalIPs: # 外部 IP
- 1.2.3.4
externalName: xxx.example.com # ExternalName 类型
sessionAffinity: None/ClientIP # 会话亲和性
sessionAffinityConfig:
clientIP:
timeoutSeconds: 10800
loadBalancerIP: 1.2.3.4 # 指定 LB IP
loadBalancerSourceRanges: # LB 来源 IP 限制
- 10.0.0.0/8
externalTrafficPolicy: Cluster/Local # 外部流量策略
internalTrafficPolicy: Cluster/Local # 内部流量策略
healthCheckNodePort: 30000 # 健康检查端口
publishNotReadyAddresses: false # 是否发布未就绪地址
4.3 Ingress 完整配置项清单
# ═══════════════════════════════════════════════════════════════════════════════
# Ingress 所有配置项清单
# ═══════════════════════════════════════════════════════════════════════════════
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: xxx
namespace: xxx
annotations:
# Ingress Controller 类型
kubernetes.io/ingress.class: nginx
# SSL 重定向
nginx.ingress.kubernetes.io/ssl-redirect: "true"
# 自动申请证书
cert-manager.io/cluster-issuer: letsencrypt-prod
# URL 重写
nginx.ingress.kubernetes.io/rewrite-target: /$1
# 请求体大小
nginx.ingress.kubernetes.io/proxy-body-size: "100m"
# 超时配置
nginx.ingress.kubernetes.io/proxy-connect-timeout: "60"
nginx.ingress.kubernetes.io/proxy-send-timeout: "60"
nginx.ingress.kubernetes.io/proxy-read-timeout: "60"
# 限流
nginx.ingress.kubernetes.io/limit-rps: "100"
nginx.ingress.kubernetes.io/limit-connections: "50"
# 跨域
nginx.ingress.kubernetes.io/enable-cors: "true"
nginx.ingress.kubernetes.io/cors-allow-origin: "*"
# 金丝雀发布
nginx.ingress.kubernetes.io/canary: "true"
nginx.ingress.kubernetes.io/canary-weight: "10"
nginx.ingress.kubernetes.io/canary-header: "canary"
nginx.ingress.kubernetes.io/canary-header-value: "true"
spec:
ingressClassName: nginx # Ingress 类名
tls: # HTTPS 配置
- hosts:
- example.com
- www.example.com
secretName: tls-secret
defaultBackend: # 默认后端
service:
name: default-service
port:
number: 80
rules:
- host: example.com # 域名
http:
paths:
- path: / # 路径
pathType: Prefix/Exact/ImplementationSpecific
backend:
service:
name: frontend
port:
number: 80
# name: http # 或用端口名
- path: /api
pathType: Prefix
backend:
service:
name: backend
port:
number: 8080
4.4 ConfigMap 和 Secret 配置项清单
# ═══════════════════════════════════════════════════════════════════════════════
# ConfigMap
# ═══════════════════════════════════════════════════════════════════════════════
apiVersion: v1
kind: ConfigMap
metadata:
name: xxx
namespace: xxx
data: # 键值对数据
key1: value1
key2: value2
config.yaml: | # 配置文件内容
server:
port: 8080
binaryData: # 二进制数据(base64)
key: SGVsbG8=
immutable: false # 是否不可变
---
# ═══════════════════════════════════════════════════════════════════════════════
# Secret
# ═══════════════════════════════════════════════════════════════════════════════
apiVersion: v1
kind: Secret
metadata:
name: xxx
namespace: xxx
type: Opaque # 类型
# type: kubernetes.io/tls # TLS 证书
# type: kubernetes.io/dockerconfigjson # Docker 凭证
# type: kubernetes.io/basic-auth # 用户名密码
# type: kubernetes.io/ssh-auth # SSH 密钥
stringData: # 明文数据(自动编码)
username: admin
password: secret
data: # Base64 编码数据
username: YWRtaW4=
password: c2VjcmV0
immutable: false
4.5 HPA 配置项清单
# ═══════════════════════════════════════════════════════════════════════════════
# HorizontalPodAutoscaler(水平自动扩缩)
# ═══════════════════════════════════════════════════════════════════════════════
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: xxx
namespace: xxx
spec:
scaleTargetRef: # 扩缩目标
apiVersion: apps/v1
kind: Deployment
name: backend
minReplicas: 2 # 最小副本数
maxReplicas: 10 # 最大副本数
metrics: # 扩缩指标
- type: Resource # 资源指标
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70 # CPU 使用率 70% 触发扩容
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 80 # 内存使用率 80% 触发扩容
- type: Pods # Pod 指标
pods:
metric:
name: requests-per-second
target:
type: AverageValue
averageValue: "1k"
- type: External # 外部指标
external:
metric:
name: queue_messages_ready
selector:
matchLabels:
queue: worker
target:
type: AverageValue
averageValue: "30"
behavior: # 扩缩行为
scaleUp:
stabilizationWindowSeconds: 0 # 扩容稳定窗口
policies:
- type: Percent
value: 100 # 每次最多扩容 100%
periodSeconds: 15
- type: Pods
value: 4 # 每次最多扩容 4 个
periodSeconds: 15
selectPolicy: Max
scaleDown:
stabilizationWindowSeconds: 300 # 缩容稳定窗口(5分钟)
policies:
- type: Percent
value: 10 # 每次最多缩容 10%
periodSeconds: 60
五、配置使用场景清单
┌─────────────────────────────────────────────────────────────────────────────────┐
│ K8s 配置使用场景速查表 │
├─────────────────────────────────────────────────────────────────────────────────┤
│ │
│ ════════════════════════════════════════════════════════════════════════════ │
│ 部署应用 │
│ ════════════════════════════════════════════════════════════════════════════ │
│ ┌────────────────────────────────┬───────────────────────────────────────────┐│
│ │ 场景 │ 使用的资源 ││
│ ├────────────────────────────────┼───────────────────────────────────────────┤│
│ │ 部署 Web 应用/API │ Deployment + Service + Ingress ││
│ │ 部署有状态应用(数据库) │ StatefulSet + Service + PVC ││
│ │ 每个节点运行一个 Pod │ DaemonSet ││
│ │ 运行一次性任务 │ Job ││
│ │ 运行定时任务 │ CronJob ││
│ └────────────────────────────────┴───────────────────────────────────────────┘│
│ │
│ ════════════════════════════════════════════════════════════════════════════ │
│ 暴露服务 │
│ ════════════════════════════════════════════════════════════════════════════ │
│ ┌────────────────────────────────┬───────────────────────────────────────────┐│
│ │ 场景 │ 使用的资源 ││
│ ├────────────────────────────────┼───────────────────────────────────────────┤│
│ │ 只需集群内访问 │ Service (ClusterIP) ││
│ │ 需要外部访问(测试) │ Service (NodePort) ││
│ │ 需要外部访问(云环境) │ Service (LoadBalancer) ││
│ │ HTTP/HTTPS 入口(推荐) │ Ingress ││
│ │ 多服务共享入口 │ Ingress + 路由规则 ││
│ │ HTTPS + 自动证书 │ Ingress + cert-manager ││
│ └────────────────────────────────┴───────────────────────────────────────────┘│
│ │
│ ════════════════════════════════════════════════════════════════════════════ │
│ 配置管理 │
│ ════════════════════════════════════════════════════════════════════════════ │
│ ┌────────────────────────────────┬───────────────────────────────────────────┐│
│ │ 场景 │ 使用的资源 ││
│ ├────────────────────────────────┼───────────────────────────────────────────┤│
│ │ 存储非敏感配置 │ ConfigMap ││
│ │ 存储密码、密钥 │ Secret ││
│ │ 存储 TLS 证书 │ Secret (kubernetes.io/tls) ││
│ │ 存储 Docker 凭证 │ Secret (kubernetes.io/dockerconfigjson) ││
│ └────────────────────────────────┴───────────────────────────────────────────┘│
│ │
│ ════════════════════════════════════════════════════════════════════════════ │
│ 存储 │
│ ════════════════════════════════════════════════════════════════════════════ │
│ ┌────────────────────────────────┬───────────────────────────────────────────┐│
│ │ 场景 │ 使用的资源 ││
│ ├────────────────────────────────┼───────────────────────────────────────────┤│
│ │ 持久化存储 │ PersistentVolumeClaim ││
│ │ 临时存储(Pod 删除即丢失) │ emptyDir ││
│ │ 宿主机目录 │ hostPath ││
│ │ 云盘(阿里云) │ PVC + StorageClass (alicloud-disk) ││
│ │ NFS │ PV + PVC ││
│ └────────────────────────────────┴───────────────────────────────────────────┘│
│ │
│ ════════════════════════════════════════════════════════════════════════════ │
│ 调度控制 │
│ ════════════════════════════════════════════════════════════════════════════ │
│ ┌────────────────────────────────┬───────────────────────────────────────────┐│
│ │ 场景 │ 使用的配置 ││
│ ├────────────────────────────────┼───────────────────────────────────────────┤│
│ │ 调度到特定节点 │ nodeSelector 或 nodeAffinity ││
│ │ Pod 分散到不同节点 │ podAntiAffinity ││
│ │ Pod 调度到一起 │ podAffinity ││
│ │ 调度到有污点的节点 │ tolerations ││
│ └────────────────────────────────┴───────────────────────────────────────────┘│
│ │
│ ════════════════════════════════════════════════════════════════════════════ │
│ 自动扩缩 │
│ ════════════════════════════════════════════════════════════════════════════ │
│ ┌────────────────────────────────┬───────────────────────────────────────────┐│
│ │ 场景 │ 使用的资源 ││
│ ├────────────────────────────────┼───────────────────────────────────────────┤│
│ │ 根据 CPU/内存自动扩缩 │ HorizontalPodAutoscaler ││
│ │ 根据自定义指标扩缩 │ HPA + Prometheus Adapter ││
│ │ 自动调整 resources │ VerticalPodAutoscaler ││
│ └────────────────────────────────┴───────────────────────────────────────────┘│
│ │
│ ════════════════════════════════════════════════════════════════════════════ │
│ 权限控制 │
│ ════════════════════════════════════════════════════════════════════════════ │
│ ┌────────────────────────────────┬───────────────────────────────────────────┐│
│ │ 场景 │ 使用的资源 ││
│ ├────────────────────────────────┼───────────────────────────────────────────┤│
│ │ Pod 身份标识 │ ServiceAccount ││
│ │ 命名空间内权限 │ Role + RoleBinding ││
│ │ 集群级权限 │ ClusterRole + ClusterRoleBinding ││
│ │ 网络隔离 │ NetworkPolicy ││
│ └────────────────────────────────┴───────────────────────────────────────────┘│
│ │
└─────────────────────────────────────────────────────────────────────────────────┘
六、kubectl 常用命令
# ═══════════ 查看资源 ═══════════
kubectl get pods/svc/deploy/ingress -n <namespace>
kubectl get all -n <namespace>
kubectl describe pod <name> -n <namespace>
# ═══════════ 创建/更新 ═══════════
kubectl apply -f xxx.yaml
kubectl create -f xxx.yaml
# ═══════════ 删除 ═══════════
kubectl delete -f xxx.yaml
kubectl delete pod <name> -n <namespace>
# ═══════════ 日志 ═══════════
kubectl logs <pod> -n <namespace>
kubectl logs <pod> -c <container> -n <namespace>
kubectl logs -f <pod> --tail=100
# ═══════════ 进入容器 ═══════════
kubectl exec -it <pod> -n <namespace> -- bash
kubectl exec -it <pod> -c <container> -- bash
# ═══════════ 扩缩容 ═══════════
kubectl scale deployment <name> --replicas=5
# ═══════════ 更新镜像 ═══════════
kubectl set image deployment/<name> <container>=<new-image>
# ═══════════ 回滚 ═══════════
kubectl rollout undo deployment/<name>
kubectl rollout history deployment/<name>
# ═══════════ 查看 API 资源 ═══════════
kubectl api-resources
kubectl explain deployment.spec.strategy
更多推荐
所有评论(0)