跳到主要内容

k8s存储相关

1.存储分类

image-20250511142232627

2.configMap类型

ConfigMap 功能在 Kubernetes1.2 版本中引入,用于向容器中注入配置信息。

a.configMap-创建指令

--from-file--from-env-file 的区别

特性--from-file--from-env-file
文件格式任意格式必须是 key=value 格式
ConfigMap 结构键为文件名,值为文件内容键值对由每行 key=value 拆分
典型用途挂载配置文件到容器卷注入环境变量到容器
多文件支持支持仅支持单个文件
内容解析不解析内容,直接保存解析每行 key=value
# --from-file 创建
kubectl create configmap game-config --from-file=config.file

# --from-env-file 创建
kubectl create configmap env-config --from-env-file=config.env

# --from-literal 创建
kubectl create configmap literal-config --from-literal=name=dave --from-literal=password=pass

b-e. configMap 使用方式

  • 作为环境变量:通过 valueFrom.configMapKeyRef 注入
  • 作为启动命令:通过 $(KEY_NAME) 引用
  • 挂载为配置文件:通过 volume 挂载到容器路径
  • 热更新:Volume 方式支持热更新,Env 方式不支持

f. 设置为不可更改

kubectl patch cm default-nginx --patch '{"immutable": true}'

3.Secret类型

Secret 对象用来保存敏感信息,如密码、OAuth 令牌和 SSH 密钥。

a. Secret 类型

image-20250511184623691

b. Opaque 类型使用

# 创建 base64 编码
echo -n "admin" | base64
# YWRtaW4=

# 创建 Secret
cat > my-secret.yml <<EOF
apiVersion: v1
kind: Secret
metadata:
name: mysecret
type: Opaque
data:
password: c2RmZXdyYQ==
username: YWRtaW4=
EOF

Secret 支持 ENV 和 Volume 两种挂载方式,Volume 方式支持热更新。

4.Downward API

Downward API 允许容器获取 Pod 自身的元数据信息(名称、命名空间、IP、标签等)。

# 支持 env 和 volume 两种方式
# volume 方式支持热更新

image-20250512101136184

5.Volume类型

a. emptyDir

空目录卷,Pod 内容器间共享数据,Pod 删除后数据丢失。

# 普通 emptyDir
emptyDir: {}

# 基于内存的 emptyDir(高性能)
emptyDir:
medium: Memory
sizeLimit: 500Mi

b. hostPath

将主机节点文件系统挂载到 Pod 中。

image-20250512151014857

6.PV/PVC + StatefulSet

安装 NFS 服务器

# 服务端
yum install -y nfs-utils rpcbind
mkdir /nfsdata && chmod 666 /nfsdata && chown nobody /nfsdata
cat >/etc/exports<<EOF
/nfsdata *(rw,no_root_squash,no_all_squash,sync)
EOF
systemctl start rpcbind nfs-server

部署 PV

apiVersion: v1
kind: PersistentVolume
metadata:
name: nfspv1
spec:
capacity:
storage: 1Gi
accessModes:
- ReadWriteOnce
persistentVolumeReclaimPolicy: Recycle
storageClassName: nfs
nfs:
path: /nfsdata
server: 192.168.123.88

StatefulSet + PVC 模板

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
serviceName: "nginx"
replicas: 3
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: wangyanglinux/myapp:v1.0
ports:
- containerPort: 80
name: web
volumeMounts:
- name: www
mountPath: /usr/local/nginx/html
volumeClaimTemplates:
- metadata:
name: www
spec:
accessModes: [ "ReadWriteOnce" ]
storageClassName: "nfs"
resources:
requests:
storage: 1Gi

7.StorageClass — 动态供给

部署 nfs-client-provisioner

# 1. 创建 ServiceAccount + RBAC
# 2. 部署 nfs-client-provisioner Deployment
# 3. 创建 StorageClass

image-20250512175137156