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

Docker容器无法访问公司内网数据库问题求助

问题描述

我使用Windows Docker Desktop(版本20.10.11,build dea9396),通过以下docker-compose.yml启动Tomcat容器:

version: "3.7"
services:
  tomcat:
    image: tomcat:9
    container_name: tomcat-change
    ports:
      - "18080:8080"
    volumes:
      - "./my.war:/usr/local/tomcat/webapps/my.war"
    entrypoint:
      - "catalina.sh"
      - "run"
    networks:
      - mywork

networks:
  mywork:
    name: mywork
    driver: bridge
    ipam:
      driver: default
      config:
      - subnet: 172.31.0.0/24
        gateway: 172.31.0.1

公司内网网段为172.17.xxx.xxx,本机内网IP为172.17.6.xxx,内网数据库服务器IP为172.17.1.xxx。本地直接启动服务可正常连接数据库,但Docker容器内的服务无法连接,报错:

com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host 172.17.1.xxx, port 1433 has failed. Error: "Connect timed out. 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
排查与解决步骤

1. 验证容器到宿主机的连通性

  • 进入容器执行命令:ping 172.17.6.xxx,测试能否ping通宿主机内网IP。
  • 如果能ping通,修改服务的数据库连接地址为宿主机内网IP(172.17.6.xxx):1433,同时在宿主机防火墙添加规则,允许来自Docker容器网段172.31.0.0/24的1433端口入站请求。

2. 切换Docker网络为Host模式

Windows Docker Desktop支持host网络模式,让容器直接复用宿主机网络栈,从而获得和宿主机一致的内网访问权限。修改docker-compose.yml:

version: "3.7"
services:
  tomcat:
    image: tomcat:9
    container_name: tomcat-change
    network_mode: "host"
    volumes:
      - "./my.war:/usr/local/tomcat/webapps/my.war"
    entrypoint:
      - "catalina.sh"
      - "run"

注意:使用host模式后,端口映射配置不再生效,直接通过http://localhost:8080访问Tomcat即可。

3. 调整数据库服务器防火墙规则

确认数据库服务器的防火墙是否允许来自Docker容器网段172.31.0.0/24的1433端口连接。如果原有规则仅放行公司内网172.17.0.0/16的流量,需添加新规则允许172.31.0.0/24网段的访问。

4. 配置Docker内网DNS

进入容器执行nslookup 172.17.1.xxx,验证地址解析是否正常。如果解析失败,在Docker Desktop的Settings -> Docker Engine中配置公司内网DNS服务器:

{
  "dns": ["xxx.xxx.xxx.xxx"]  # 替换为公司内网DNS服务器IP
}

修改完成后重启Docker Desktop。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 18:31:02