113 lines
2.4 KiB
Markdown
113 lines
2.4 KiB
Markdown
# PostgreSQL 16 K3s 部署配置
|
||
|
||
## 文件说明
|
||
|
||
- `namespace.yaml` - 创建 infrastructure 命名空间
|
||
- `secret.yaml` - 存储 PostgreSQL 密码等敏感信息
|
||
- `configmap.yaml` - 存储初始化脚本(创建用户和 300 个数据库)
|
||
- `pvc.yaml` - 持久化存储声明(20Gi)
|
||
- `deployment.yaml` - PostgreSQL 16 部署配置
|
||
- `service.yaml` - 服务暴露(ClusterIP + NodePort)
|
||
|
||
## 部署步骤
|
||
|
||
### 1. 部署所有资源
|
||
|
||
```bash
|
||
kubectl apply -f namespace.yaml
|
||
kubectl apply -f secret.yaml
|
||
kubectl apply -f configmap.yaml
|
||
kubectl apply -f pvc.yaml
|
||
kubectl apply -f deployment.yaml
|
||
kubectl apply -f service.yaml
|
||
```
|
||
|
||
或者一次性部署:
|
||
|
||
```bash
|
||
kubectl apply -f .
|
||
```
|
||
|
||
### 2. 查看部署状态
|
||
|
||
```bash
|
||
# 查看 Pod 状态
|
||
kubectl get pods -n infrastructure
|
||
|
||
# 查看 Pod 日志
|
||
kubectl logs -n infrastructure -l app=pg16 -f
|
||
|
||
# 查看服务
|
||
kubectl get svc -n infrastructure
|
||
```
|
||
|
||
### 3. 访问数据库
|
||
|
||
**集群内访问:**
|
||
```bash
|
||
# 使用 ClusterIP 服务
|
||
psql -h pg16.infrastructure.svc.cluster.local -U postgres -p 5432
|
||
```
|
||
|
||
**集群外访问:**
|
||
```bash
|
||
# 使用 NodePort(端口 30432)
|
||
psql -h <节点IP> -U postgres -p 30432
|
||
```
|
||
|
||
**使用 kubectl port-forward:**
|
||
```bash
|
||
kubectl port-forward -n infrastructure svc/pg16 5432:5432
|
||
psql -h localhost -U postgres -p 5432
|
||
```
|
||
|
||
## 配置说明
|
||
|
||
### 存储
|
||
- 使用 k3s 默认的 `local-path` StorageClass
|
||
- 默认申请 20Gi 存储空间
|
||
- 数据存储在 `/var/lib/postgresql/data/pgdata`
|
||
|
||
### 资源限制
|
||
- 请求:512Mi 内存,0.5 核 CPU
|
||
- 限制:2Gi 内存,2 核 CPU
|
||
|
||
### 初始化
|
||
- 自动创建超级用户 `fei`
|
||
- 自动创建 300 个数据库(pg001 到 pg300)
|
||
|
||
### 服务暴露
|
||
- **ClusterIP 服务**:集群内部访问,服务名 `pg16`
|
||
- **NodePort 服务**:集群外部访问,端口 `30432`
|
||
|
||
## 数据迁移
|
||
|
||
### 从现有 Docker 数据迁移
|
||
|
||
如果你有现有的 pgdata 数据,可以:
|
||
|
||
1. 先部署不带数据的 PostgreSQL
|
||
2. 停止 Pod
|
||
3. 将数据复制到 PVC 对应的主机路径
|
||
4. 重启 Pod
|
||
|
||
```bash
|
||
# 查找 PVC 对应的主机路径
|
||
kubectl get pv
|
||
|
||
# 停止 Pod
|
||
kubectl scale deployment pg16 -n infrastructure --replicas=0
|
||
|
||
# 复制数据到主机路径(通常在 /var/lib/rancher/k3s/storage/)
|
||
# 然后重启
|
||
kubectl scale deployment pg16 -n infrastructure --replicas=1
|
||
```
|
||
|
||
## 卸载
|
||
|
||
```bash
|
||
kubectl delete -f .
|
||
```
|
||
|
||
注意:删除 PVC 会删除所有数据,请谨慎操作。
|