本文介绍一种简单、稳定、可直接部署的 PostgreSQL 16 在 Kubernetes 中的部署方式,适合:
- 单机 K8s / k3s
- 开发、测试、内部业务环境
- 仅 集群内部访问 的数据库场景
特点一句话总结:少配置、不踩坑、一次就能跑起来。
一、方案说明
本方案具备以下特点:
- 使用
StatefulSet(保证数据库身份稳定) - 使用
hostPath持久化数据(简单直观) - 使用
initContainer修复权限(避免常见init-perms BackOff) - PostgreSQL 监听所有地址
pg_hba.conf完全放开(仅建议集群内使用)- 通过
ClusterIP Service访问,不暴露公网
二、部署结构
Namespace: flash
├── Secret (数据库名 / 用户 / 密码)
├── ConfigMap (postgresql.conf / pg_hba.conf)
├── StatefulSet (PostgreSQL 16)
└── Service (ClusterIP)
数据库访问地址:
postgresql.flash.svc:5432
三、完整部署 YAML
将下面内容保存为 postgresql-open.yaml,直接部署即可。
apiVersion: v1
kind: Secret
metadata:
name: postgresql-secret
namespace: flash
type: Opaque
stringData:
POSTGRES_DB: eladmin
POSTGRES_USER: postgres
POSTGRES_PASSWORD: "ChangeMe123"
---
apiVersion: v1
kind: ConfigMap
metadata:
name: postgresql-config
namespace: flash
data:
postgresql.conf: |
listen_addresses = '*'
port = 5432
pg_hba.conf: |
local all all trust
host all all 0.0.0.0/0 md5
host all all ::/0 md5
---
apiVersion: v1
kind: Service
metadata:
name: postgresql
namespace: flash
spec:
type: ClusterIP
selector:
app: postgresql
ports:
- port: 5432
targetPort: 5432
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: postgresql
namespace: flash
spec:
serviceName: postgresql
replicas: 1
selector:
matchLabels:
app: postgresql
template:
metadata:
labels:
app: postgresql
spec:
securityContext:
fsGroup: 999
initContainers:
- name: init-perms
image: busybox:1.36
securityContext:
runAsUser: 0
command: ["/bin/sh","-c"]
args:
- mkdir -p /var/lib/postgresql/data && chown -R 999:999 /var/lib/postgresql/data
volumeMounts:
- name: pg-data
mountPath: /var/lib/postgresql/data
containers:
- name: postgresql
image: postgres:16
securityContext:
runAsUser: 999
envFrom:
- secretRef:
name: postgresql-secret
env:
- name: PGDATA
value: /var/lib/postgresql/data/pgdata
ports:
- containerPort: 5432
args:
- "-c"
- "config_file=/etc/postgresql/postgresql.conf"
- "-c"
- "hba_file=/etc/postgresql/pg_hba.conf"
volumeMounts:
- name: pg-data
mountPath: /var/lib/postgresql/data
- name: pg-config
mountPath: /etc/postgresql/postgresql.conf
subPath: postgresql.conf
- name: pg-config
mountPath: /etc/postgresql/pg_hba.conf
subPath: pg_hba.conf
volumes:
- name: pg-data
hostPath:
path: /data/postgresql
type: DirectoryOrCreate
- name: pg-config
configMap:
name: postgresql-config
四、部署与验证
kubectl apply -f postgresql-open.yaml
kubectl -n flash get pods
验证数据库:
kubectl -n flash exec -it postgresql-0 -- psql -U postgres -d eladmin
五、注意事项
- 仅用于内网 / 集群内部
- 不要直接暴露到公网
- 若用于生产,建议改用 PVC + 收紧
pg_hba.conf











