解决 PostgreSQL 在 Docker 中报错 could not resize shared memory
分析 Docker 运行 PostgreSQL 报 could not resize shared memory 诱因,详解 /dev/shm 容器扩容配置。
问题现象
在 Docker 容器或 Kubernetes Pod 中运行 PostgreSQL 10+ 并发执行并行查询(Parallel Query)时崩溃:
ERROR: could not resize shared memory segment "/PostgreSQL.123456" to 104857600 bytes: No space left on device
触发根因
Docker 容器默认给 /dev/shm(POSIX 共享内存)分配的大小仅有 64MB。PostgreSQL 现代并行查询在多 Worker 线程间共享数据块时,极易耗尽此 64MB 上限。
解决方案
方案一:在 Docker 中通过 --shm-size 调大共享内存
docker run -d --shm-size=1g -e POSTGRES_PASSWORD=mysecret postgres:15
在 docker-compose.yml 中:
services:
db:
image: postgres:15
shm_size: '1gb'
方案二:在 Kubernetes 中挂载 emptyDir 内存卷
volumeMounts:
- mountPath: /dev/shm
name: dshm
volumes:
- name: dshm
emptyDir:
medium: Memory
sizeLimit: 1Gi
验证方法
再次执行大型并行聚合查询,共享内存正常分配,不再触发 OOM 崩溃。


