Spring Boot连接Docker部署的PostgreSQL时出现pg_hba.conf无匹配条目及加密问题求助
你遇到的这个错误 FATAL: no pg_hba.conf entry for host "172.21.144.1", user "smath", database "customer", no encryption,核心原因有两个:一是你自定义的pg_hba.conf没有被Docker容器中的PostgreSQL加载,二是你的JDBC连接URL没有明确指定加密模式,导致PostgreSQL拒绝无加密的连接。下面是具体的解决步骤:
一、确保自定义pg_hba.conf被Docker容器加载
你的docker-compose.yml中没有将本地修改的pg_hba.conf挂载到PostgreSQL容器中,所以容器使用的还是默认配置,你的规则根本没生效。修改docker-compose.yml的postgres服务部分:
services: postgres: container_name: postgres image: postgres environment: POSTGRES_USER: smath POSTGRES_PASSWORD: smath PGDATA: /data/postgres volumes: - postgres:/data/postgres # 挂载本地pg_hba.conf到容器对应路径,路径需和你本地文件位置匹配 - ./pg_hba.conf:/var/lib/postgresql/data/pg_hba.conf ports: - "5432:5432" networks: - postgres restart: unless-stopped # pgadmin部分保持不变
注意:如果你的
pg_hba.conf和docker-compose.yml在同一目录下,用./pg_hba.conf即可。首次挂载前需要删除旧容器和数据卷(执行docker-compose down -v),否则可能因权限问题导致配置不生效。
二、调整pg_hba.conf的规则顺序
PostgreSQL的pg_hba.conf是按从上到下的顺序匹配规则的,更具体的规则应该放在前面。修改你的pg_hba.conf,把针对smath用户和customer数据库的规则移到最顶部:
# TYPE DATABASE USER ADDRESS METHOD # 优先匹配特定用户和数据库的连接 host customer smath 172.21.144.1/32 md5 # "local" is for Unix domain socket connections only local all all trust # IPv4 local connections: host all all 0.0.0.0/0 scram-sha-256 # IPv6 local connections: host all all ::1/128 scram-sha-256
这里把172.21.144.1改成172.21.144.1/32,确保是精确匹配单个IP。
三、修改Spring Boot的JDBC连接URL,指定加密模式
错误提示里提到no encryption,说明PostgreSQL期望连接使用加密,但你的JDBC URL没有配置。修改application.yml中的datasource.url,添加sslmode=disable来禁用加密(适合开发环境):
spring: datasource: username: 'smath' url: jdbc:postgresql://postgres:5432/customer?sslmode=disable password: 'smath'
如果是生产环境,你可以配置启用加密,但开发阶段先禁用更方便测试。
四、重启服务验证
- 停止并删除旧的容器和数据卷:
docker-compose down -v
- 重新启动容器:
docker-compose up -d
- 启动Spring Boot应用,检查是否能正常连接数据库。
你还可以通过docker exec -it postgres cat /var/lib/postgresql/data/pg_hba.conf命令,验证容器内的pg_hba.conf是否已经是你修改后的内容,确保挂载生效。
内容的提问来源于stack exchange,提问作者Smath Cadet

