You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows11下Spring Boot无法连接WSL2中Docker部署的PostgreSQL

问题

在Windows 11的WSL2中通过Docker启动PostgreSQL后,本地运行的Spring Boot项目连接数据库时出现认证失败错误:

org.postgresql.util.PSQLException: FATAL: Password authentication failed for user 'user'
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.exception.GenericJDBCException: Unable to open JDBC Connection for DDL execution [org.postgresql.util.PSQLException: FATAL: Password authentication failed for user 'user']

Docker Compose配置:

services:
  postgres:
    image: 'postgres:latest'
    environment:
      - 'POSTGRES_DB=tennis_db'
      - 'POSTGRES_PASSWORD=1234'
      - 'POSTGRES_USER=user'
    ports:
      - '5432'

  pgadmin:
    image: 'dpage/pgadmin4:latest'
    environment:
      PGADMIN_DEFAULT_EMAIL: admin@gmail.com
      PGADMIN_DEFAULT_PASSWORD: 1234
      PGADMIN_LISTEN_PORT: 5050
    ports:
      - '5050:5050'

Spring Boot的application.properties配置:

spring.application.name=tennis
spring.datasource.url=jdbc:postgresql://localhost:5432/tennis_db
spring.datasource.username=user
spring.datasource.password=1234
spring.jpa.generate-ddl=true
spring.jpa.open-in-view=false
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
server.port=8081
解决方法

1. 修复PostgreSQL容器的端口映射

当前Docker Compose中PostgreSQL的端口配置- '5432'是随机映射到Windows主机的某个端口,并非固定绑定5432端口。修改为固定映射:

ports:
  - '5432:5432'

修改后重启容器:docker-compose down && docker-compose up -d

2. 替换localhost为WSL2的IP地址

如果Spring Boot在Windows主机运行,直接用localhost可能无法穿透WSL2网络。在WSL2终端执行hostname -I获取WSL2的IP地址,然后修改application.properties中的数据库URL:

spring.datasource.url=jdbc:postgresql://<WSL2_IP>:5432/tennis_db

将<WSL2_IP>替换为实际获取到的IP(通常是172开头的地址)。

3. 验证PostgreSQL容器的凭证正确性

进入PostgreSQL容器,手动验证用户和密码是否有效:

  1. 查看运行中的容器ID:docker ps
  2. 进入容器:docker exec -it <postgres_container_id> bash
  3. 登录PostgreSQL:psql -U user -d tennis_db,输入密码1234,如果能成功登录则凭证无误。

4. 检查容器日志确认初始化状态

查看PostgreSQL容器的启动日志,确认用户和数据库是否正常创建:

docker logs <postgres_container_id>

日志中如果出现类似database system is ready to accept connections以及CREATE ROLE user、CREATE DATABASE tennis_db的信息,说明初始化正常。


内容的提问来源于stack exchange,提问作者obela06

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 17:41:21