Files
Deploy-Laboratory/docs/03-05-k3s-local-path-pvc.md
2026-03-21 04:36:06 +08:00

52 lines
2.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 03-06-k3s local-path PVC 本地持久化
> K3s 自带的 **local-path-provisioner**:通过 PVC 自动创建本地 PersistentVolume适用于单副本应用、缓存、日志等无需 NFS 或 Longhorn。
## 与 NFS / Longhorn 的区别
| 方式 | 共享 | 适用场景 |
|------|------|----------|
| **local-path**(本页) | 否,单节点 | 单副本应用Traefik acme.json、单机数据库等Pod 固定调度到同一节点 |
| **NFS**`03-08` | 是,多节点读写 | 多副本共享目录、需跨节点访问 |
| **Longhorn**`03-09` | 块存储CSI | 重状态系统、快照/备份、生产推荐 |
## 前置条件
- K3s 已安装local-path-provisioner 默认启用)
- 无额外组件,`kubectl get storageclass` 可见 `local-path`(通常为默认)
## 操作步骤
### 1. 清单PVC + Deployment
**唯一真源**[`ansible/files/local-path-demo/local-path-pvc-demo.yaml`](../ansible/files/local-path-demo/local-path-pvc-demo.yaml)(含 PVC `local-pvc-demo``nginx-local-pvc-demo` Deployment`storageClassName` 可省略K3s 默认多为 `local-path`)。
### 2. 应用与验证
```bash
kubectl apply -f ansible/files/local-path-demo/local-path-pvc-demo.yaml
kubectl get pv,pvc
kubectl get pod -o wide
kubectl exec deploy/nginx-local-pvc-demo -- sh -c 'echo hello > /usr/share/nginx/html/test.txt'
kubectl delete pod -l app=nginx-local-pvc-demo
kubectl exec deploy/nginx-local-pvc-demo -- cat /usr/share/nginx/html/test.txt # 应仍为 hello
```
## 注意事项
- **绑定到节点**PV 创建在 Pod 首次调度到的节点上Pod 重建后仍会调度到该节点provisioner 会打 nodeAffinity
- **单副本**`ReadWriteOnce`,同一 PVC 只能被同一节点上的一个 Pod 挂载;多副本需 NFS 或 Longhorn
- **数据路径**:默认在 K3s `--data-dir` 下的 `storage`,如 `/var/lib/rancher/k3s/storage``/storage`
- **回收策略**`Delete`,删除 PVC 时 PV 及本地目录会被清理
## Traefik acme.json 示例
若希望 Traefik 的 ACME 证书走 local-path PVC需在 HelmChartConfig 的 values 中为 Traefik 配置 volume 与 volumeMount`03-02-k3s-traefik-acme.md` 可选配置)。多数场景下,配合 `nodeSelector` 固定 Traefik 到同一节点,再用 hostPath 或 local-path 均可;无 hostPath 时 K3s 默认会为 Traefik 挂 emptyDir 或默认卷。
## 下一步
- `03-06-k3s-使用nfs存储.md`:需多节点共享时
- `03-07-k3s-longhorn-持久化存储.md`:重状态、快照、备份