Docker部署PostgreSQL 14连接失败及本地运行报错求助
环境版本信息
- Ubuntu 22.04
- Rails 5.2.6
- Ruby 2.6.10
- PostgreSQL 14(部署于Docker容器)
问题1:Docker部署PostgreSQL 14时的连接错误
执行rake db:migrate、rake db:create或psql -h 127.0.0.1 -U user时出现以下错误:
PG::ConnectionBad: connection to server at "127.0.0.1", port 5432 failed: server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
解决方法
- 检查容器运行状态:执行
docker ps确认PG容器是否正常运行,未启动则用docker start <容器ID/名称>启动;若容器崩溃,执行docker logs <容器ID/名称>查看崩溃原因(比如挂载目录权限、环境变量配置错误)。 - 确认端口映射配置:启动容器时必须包含
-p 5432:5432参数,否则本地无法通过127.0.0.1访问容器内的PG服务。 - 调整PostgreSQL远程连接配置:
- 进入容器:
docker exec -it <容器ID/名称> bash - 修改
postgresql.conf:设置listen_addresses = '*' - 修改
pg_hba.conf:添加规则host all all 0.0.0.0/0 md5(允许所有IP以密码方式连接) - 重启容器:
docker restart <容器ID/名称>
- 进入容器:
- 核对Rails数据库配置:确保
config/database.yml中的host为127.0.0.1、port为5432,username和password与容器启动时设置的POSTGRES_USER、POSTGRES_PASSWORD环境变量完全一致。
问题2:本地运行PostgreSQL时的两类错误
执行psql时出现以下错误:
psql: error: connection to server at "localhost" (127.0.0.1), port 5432 failed: could not initiate GSSAPI security context: Unspecified GSS failure. Minor code may provide more information: Server not found in Kerberos database
connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: database "DATABSE" does not exist
解决方法
针对GSSAPI认证错误
- 临时跳过GSSAPI认证:执行psql时添加
-g参数,命令改为psql -h localhost -U user -g。 - 永久修改认证规则:
- 编辑
/etc/postgresql/14/main/pg_hba.conf,将本地连接的认证方式从gssenc改为md5,例如:host all all 127.0.0.1/32 md5 - 重启本地PG服务:
sudo systemctl restart postgresql
- 编辑
针对数据库不存在错误
- 创建指定数据库:先以超级用户登录PG:
psql -U postgres,执行CREATE DATABASE DATABSE;(注意检查拼写是否应为DATABASE)。 - 连接已存在的数据库:执行psql时明确指定默认存在的数据库,例如
psql -h localhost -U user -d postgres。
内容的提问来源于stack exchange,提问作者Kiran Kumawat
相关产品推荐
相关产品推荐

