docker容器间连不上mysql

问题描述

docker-compose 部署应用程序和mysql,但是应用程序连不上mysql

version: '3'
services:

  template:
    build: ../template
    ports:
      - "8083:8082"
    networks:
      - channel
    links:
      - mysql:mysql
    depends_on:
      - mysql
    container_name: sctemplate
    volumes:
      - ../template/data:/var/data

  mysql:
    image: mysql:5.7
    environment:
      - MYSQL_ROOT_PASSWORD=root
    ports:
      - "33060:3306"
    networks:
      - channel
    container_name: mysql
    volumes:
      - ../mysql/my.cnf:/etc/mysql/my.cnf:ro
  
  redis:
    image: redis:5.0.4
    container_name: redis

networks:
  channel:

上面是 docker-compose.yml 的代码,主要启动了template和mysql两个服务,并通过 links连接。

在Java项目中

spring.datasource.url=jdbc:mysql://mysql:3306/sc?serverTimezone=Asia/Shanghai&characterEncoding=utf8&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=root

项目可以正常启动,但是调用接口时,总是报错

"nested exception is org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
### The error may exist in URL [jar:file:/scTemplate.jar!/BOOT-INF/classes!/mapper/ScUserMapper.xml]
### The error may involve com.fw.sf.api.dao.ScUserDao.selectBySelective
### The error occurred while executing a query
### Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server."

使用 telnet 连接 mysql 3306

clipboard.png

可以telnet 通,但是,就是web应用里 就是连不上

请问,问题出在哪里

阅读 10.1k
3 个回答

关闭宿主机防火墙,重启下docker试下!!!!!

我也遇到了这个问题,有解决了吗?

新手上路,请多包涵

问题解决了没

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏