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

Tomcat Docker镜像中JDBC Driver未找到问题排查求助

解决Tomcat Docker部署Spring应用时的"JDBC driver not found"错误

核心问题分析

你遇到的错误大概率不是驱动包缺失,而是Docker容器内的数据库连接地址错误,以及可能的驱动类配置问题。以下是具体的排查和解决步骤:


1. 修正数据库URL的主机地址

在Docker容器内,localhost指向容器自身,而非宿主机的Postgres服务。根据你的Postgres部署方式调整URL:

  • 如果Postgres运行在宿主机:
    将URL中的localhost替换为host.docker.internal(适用于Windows/macOS的Docker Desktop),或者宿主机的局域网IP(如192.168.1.100):
    jdbc:postgresql://host.docker.internal:5432/postgres?currentSchema=volga&stringtype=unspecified
    
  • 如果Postgres也用Docker容器运行:
    创建Docker网络并将两个容器加入同一网络,然后用Postgres容器的名称作为主机地址:
    # 创建网络
    docker network create pg-network
    # 启动Postgres容器时加入网络
    docker run --name postgres-db --network pg-network -e POSTGRES_PASSWORD=your-pwd -d postgres
    # 启动Tomcat容器时加入同一网络,URL改为postgres-db
    jdbc:postgresql://postgres-db:5432/postgres?currentSchema=volga&stringtype=unspecified
    

2. 确认驱动类配置

在Spring的配置文件(application.properties或application.yml)中显式指定驱动类,避免自动检测失败:

spring.datasource.driver-class-name=org.postgresql.Driver

3. 验证Maven依赖配置

确保Postgres驱动的依赖配置正确,scope设为runtime(运行时生效):

<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <scope>runtime</scope>
</dependency>

4. 优化Docker镜像构建(可选)

如果需要将驱动包放到Tomcat的全局lib目录,直接在Dockerfile中添加复制步骤,避免手动进入容器操作:

# 假设WAR包解压后的路径是target/compete
COPY target/compete/WEB-INF/lib/postgresql-*.jar /usr/local/tomcat/lib/

验证步骤

  1. 修改配置后,重新构建WAR包:
    mvn clean install package
    
  2. 重新构建Docker镜像并运行:
    docker build . -t spring-tomcat-app
    docker run --network pg-network -p 8080:8080 spring-tomcat-app
    
  3. 访问http://localhost:8080,若显示"Up"则说明问题解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 03:37:49