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

Docker部署SQL Server:Java连接localhost:1433遭拒绝求助

问题描述

本地通过Docker运行Microsoft SQL Server,Azure Data Studio可正常连接数据库,但Java代码尝试连接时出现以下错误:

com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: "Connection refused. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall

Java连接代码如下:

try {
    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    new ScriptRunner(DriverManager.getConnection(
                    "jdbc:sqlserver://localhost:1433;database=mars_db;user=sa;password=sysAdmin123;encrypt=false"))
                    .runScript(new BufferedReader(new FileReader(script)));
} catch (Exception e) {
    System.err.println(e);
}

build.gradle配置:

plugins {
    id 'java'
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'com.amazonaws:aws-lambda-java-core:1.2.2'
    implementation 'com.amazonaws:aws-lambda-java-events:3.11.0'
    testImplementation 'junit:junit:4.13.2'
    implementation 'com.microsoft.sqlserver:mssql-jdbc:12.4.1.jre11'

    implementation 'org.mybatis:mybatis:3.5.13'
}

sourceCompatibility = 11
targetCompatibility = 11
排查与解决步骤
  • 确认Docker端口映射正确性:执行docker ps查看SQL Server容器的端口映射,确保宿主机1433端口已映射到容器内的1433端口。如果宿主机用了其他端口(如1434)映射容器1433,需修改JDBC连接串中的端口号。
  • 检查防火墙拦截规则:临时关闭本地防火墙测试连接,若能成功,说明防火墙阻止了Java进程访问1433端口,需手动添加允许规则。
  • 替换localhost为宿主机IP:部分环境下Java进程解析localhost的逻辑与Azure Data Studio不同,将连接串中的localhost替换为宿主机实际IP(如192.168.1.100)重试。
  • 验证容器内SQL Server服务状态:进入容器执行sqlcmd -S localhost -U sa -P sysAdmin123,若能正常连接,说明容器内服务正常,问题出在外部网络连接。
  • 调整JDBC连接串参数:在连接串中添加trustServerCertificate=true,避免加密相关的隐性问题:
    jdbc:sqlserver://localhost:1433;database=mars_db;user=sa;password=sysAdmin123;encrypt=false;trustServerCertificate=true
    
  • 尝试降级JDBC驱动版本:当前使用的mssql-jdbc:12.4.1.jre11可尝试降级到稳定旧版本(如11.2.3.jre11),排除版本兼容性问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 17:33:11