Files
Deploy-Laboratory/docs/03-07-k3s-longhorn-持久化存储.md
2026-03-21 04:36:06 +08:00

115 lines
3.7 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-08-k3s Longhorn 持久化存储(单节点自用生产)
> 适用:**没有 NFS**、希望在 K3s 中部署 GitLab 等“重状态”系统,并且能接受“单节点不做高可用、但要可重建/可备份”。
---
## 为什么要用 Longhorn而不是 hostPath / local-path / 容器文件系统)
- **容器文件系统**Pod 重建即丢,基本不可用
- **hostPath 固定目录**:能落盘,但和调度强绑定,迁移/扩缩容/备份都更麻烦
- **local-path PVC**`03-07`K3s 自带,单副本够用;无快照/备份,多副本需 NFS 或 Longhorn
- **LonghornCSI 块存储)**:对 K8s 来说是标准 PVC即使你只设 **副本数=1**,也能获得:
- 统一的 PVC 管理与回收策略
- 快照snapshot
- 备份backup target可推到对象存储
> 重要:单节点 + 副本=1 **不是高可用**。想要节点级容灾,需要多节点副本或备份到外部介质。
---
## 前置条件CentOS
在所有计划作为 Longhorn 存储节点的机器上安装依赖(单节点就只装这一台):
```bash
sudo yum install -y iscsi-initiator-utils nfs-utils
sudo systemctl enable --now iscsid
```
准备数据盘目录(你已有专用盘挂载到 `/storage`,建议给 Longhorn 单独目录):
```bash
sudo mkdir -p /storage/longhorn
sudo chmod 700 /storage/longhorn
```
---
## 安装 Longhorn
```bash
kubectl apply -f https://raw.githubusercontent.com/longhorn/longhorn/v1.7.2/deploy/longhorn.yaml
kubectl -n longhorn-system rollout status deploy/longhorn-ui
```
将 Longhorn 默认数据路径改到 `/storage/longhorn`
```bash
kubectl -n longhorn-system patch settings.longhorn.io default-data-path \
--type=merge -p '{"value":"/storage/longhorn"}'
```
`longhorn` 设为默认 StorageClass推荐
```bash
kubectl get storageclass
kubectl patch storageclass longhorn -p '{"metadata":{"annotations":{"storageclass.kubernetes.io/is-default-class":"true"}}}'
```
---
## 单节点“非 HA”建议配置
### 副本数
- 建议将 Longhorn 的 **默认副本数**设为 1节省空间也符合“非 HA”定位
- 需要迁移卷/临时容灾时,可手动把某个卷副本数调到 2待同步完成再调回 1
### 只让“有大盘”的节点承载数据
如果你是多节点集群但只有少数节点有 `/storage` 大盘:
- 只把这些节点加入 Longhorn 可调度存储Longhorn UI 中将其它节点的 disk 设为不可调度)
- 或者给存储节点打标签,配合工作负载的 nodeSelector/affinity让应用尽量靠近数据
> 注意:副本=1 时,卷不会“随使用自动从小盘迁到大盘”,需要你手动迁移或从源头限制调度。
---
## GitLab 这类重状态系统如何落地
原则:**所有关键组件都用 PVC**Longhorn
- **必须 PVC**PostgreSQL、Redis、Gitalyrepo、uploads/artifacts/packages、registry如启用
- **备份**
- 应用层GitLab 自带 backup+ 存储层Longhorn snapshot/backup双保险
---
## Traefik `acme.json` 如何持久化/备份(可选)
Traefik 的 ACME 状态很小,但也建议持久化以避免重建后触发频繁签发。
- **推荐**:给 Traefik 的 `/data` 使用 PVCLonghorn`acme.json` 走标准持久化
- **兜底**:定期导出 `acme.json` 备份(例如 `kubectl cp pod/<traefik-pod>:/data/acme.json ...`
---
## 验证
```bash
kubectl -n longhorn-system get pod
kubectl get pvc -A
kubectl get pv
```
---
## 下一步
- `03-05-k3s-local-path-pvc.md`:单副本、无快照需求时,用 K3s 自带 local-path 即可
- 返回 `03-09-k3s-gitops-集群配置管理.md` 或进入业务部署(如 GitLab章节