docker内无法访问MySQL

程序基于spring cloud框架,docker部署,docker内的程序死活连接不到docker内的MySQL。但是用Navicat可以连接。写个简单的jdbc也能连接成功。

心路历程:

1.猜想是MySQL问题:

  1. 连接超时问题?网上说用到durid连接池时设置超时太短,会出现连接失败情况,配置.cnf文件
    connect_timeout = 43200,wait_timeout=86400
    interactive_timeout=86400,bind-address    = 0.0.0.0
    发现均不起作用。
  2. 然后怀疑docker的MySQL镜像有问题?遂将程序连接字符串改为我们阿里云上的mysql地址,打包,部署程序ok
  3. 将程序连接字符串改为localhost不行,改为127.0.0.1不行。最后发现用本机ipv4程序正常运行
  4. 那MySQL没问题,会不会是docker问题,docker无法用localhost访问docker内的mysql服务。docker内每个程序都是单独隔离的!!!

2.猜想是docker配置问题。百度了一圈发现大意是docker-compose 为内部网络,没有回路,所以用localhost不行。而通过docker部署的mysql3306为容器的外部端口(即宿主主机端口),不是mysql的端口。

https://stackoverflow.com/questions/24319662/from-inside-of-a-docker-container-how-do-i-connect-to-the-localhost-of-the-mach?noredirect=1

3.最后解决方法:

  1. 配置docker-compose,用-links将应用与mysql连接。注意不要用depends_on(按依赖顺序启动)。
      axe-upms-admin:
        build:
          context: ./
          dockerfile: ./axe-upms/axe-upms-admin/Dockerfile
        restart: always
        environment:
          - TZ=Asia/Shanghai
        ports:
          - 9101:9101
        links:
          - axe-mysql:axe-mysql
        container_name: axe-upms-admin
        hostname: axe-upms-admin
        image: axe-upms-admin

    2.改写程序连接字符串

      datasource:
        driver-class-name: com.p6spy.engine.spy.P6SpyDriver
        username: 1
        password: 2
        #    url: jdbc:p6spy:mysql://localhost:3306/axe_admin?characterEncoding=utf8&allowPublicKeyRetrieval=true&zeroDateTimeBehavior=convertToNull&useSSL=false&allowMultiQueries=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai
        url: jdbc:p6spy:mysql://axe-mysql:3306/axe_admin?characterEncoding=utf8&allowPublicKeyRetrieval=true&zeroDateTimeBehavior=convertToNull&useSSL=false&allowMultiQueries=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai
        type: com.zaxxer.hikari.HikariDataSource

    注意将localhost改为MySQL的docker实例名axe-mysql。困扰一整天的问题搞定。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值