ANALYSIS
🚀 一、准备环境
确保你的集群运行正常:
PRTCL // BASH
# 查看节点是否全部 Readykubectl get nodes -o wide如果有多个节点,建议选择一个用于运行数据库的 StorageClass(比如 local-path、nfs 或 rook-ceph)。
🧱 二、创建命名空间与持久化存储
PRTCL // BASH
# 创建一个 YAML 文件,用于定义 PVC(PersistentVolumeClaim,持久卷声明)cat > postgres-pvc.yaml <<EOFapiVersion: v1 # API 版本,v1 表示核心 API 组(core group)kind: PersistentVolumeClaim # 资源类型为 持久卷声明(PVC)metadata: # 元数据定义部分(对象的名字、命名空间等) name: postgres-pvc # PVC 名称:postgres-pvc namespace: postgres # 所属命名空间:postgresspec: # 具体的规格说明(specification) accessModes: # 访问模式列表 - ReadWriteOnce # 访问模式:单节点读写(RWO = ReadWriteOnce) resources: # 资源请求定义 requests: # 定义 PVC 请求的最小资源 storage: 5Gi # 请求 5Gi(5GB)的存储空间EOF
# 应用该 PVC 定义文件,将其提交给 Kubernetes 集群kubectl apply -f postgres-pvc.yaml # -f 表示指定文件路径(file)🧩 三、部署 PostgreSQL(Deployment + Service)
PRTCL // BASH
# 创建 PostgreSQL 的部署文件(Deployment + Service)cat > postgres-deploy.yaml <<EOFapiVersion: apps/v1 # API 版本,apps/v1 用于 Deployment 资源kind: Deployment # 资源类型为 Deployment(部署控制器)metadata: # 元数据定义 name: postgres # Deployment 名称 namespace: postgres # 所属命名空间spec: # 规格说明 replicas: 1 # 副本数量(replicas = 实例数量) selector: # 选择器,用于匹配 Pod matchLabels: # 匹配标签(label) app: postgres # 标签键值对:app=postgres template: # Pod 模板定义 metadata: labels: # Pod 标签 app: postgres spec: # Pod 规格 containers: # 容器定义列表 - name: postgres # 容器名称 image: postgres:15 # 容器镜像版本:PostgreSQL 15 ports: # 暴露端口列表 - containerPort: 5432 # 容器内部端口(PostgreSQL 默认端口) env: # 环境变量定义 - name: POSTGRES_USER # 数据库用户名变量 value: "admin" # 设置用户名为 admin - name: POSTGRES_PASSWORD # 数据库密码变量 value: "password123" # 设置密码为 password123 - name: POSTGRES_DB # 数据库名称变量PRTCL // SH
# 部署kubectl apply -f postgres-deploy.yaml🔍 四、验证部署
PRTCL // BASH
# 查看 Pod 状态kubectl get pods -n postgres -o wide
# 查看 Service 暴露端口kubectl get svc -n postgres假设你的 Node IP 是 192.168.2.100,那么现在数据库可以从外部访问:
PRTCL // PLAINTEXT
Host: 192.168.2.100Port: 30032User: adminPassword: password123Database: mydb🧪 五、在集群内连接测试
进入 PostgreSQL 容器内部测试:
PRTCL // BASH
kubectl exec -it -n postgres deploy/postgres -- bash
# 登录数据库psql -U admin -d mydb
# 在 psql 控制台执行简单查询\l # 列出数据库\dt # 列出数据表\q # 退出⚙️ 六、删除 PostgreSQL(清理环境)
PRTCL // BASH
# 删除 Deployment、Service、PVCkubectl delete -f postgres-deploy.yamlkubectl delete -f postgres-pvc.yamlkubectl delete ns postgres作者:EchoWang
小红书:汪多多是只猫
B 站:汪多多是只猫
公众号:汪多多是只猫
R P
Rhine Lab Pioneer Division
Auth_Verified: 2026.04.08
Auth_Verified: 2026.04.08
