我正在使用Spring Boot,Hibernate和MySql。在运行应用程序时,它按预期运行得很好。但是在制作docker- compose文件并使用mysql docker image运行应用docker镜像时,会出现此错误。
错误 com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:通信链接失败java.net.ConnectException:连接被拒绝。
private Connection createConnection() throws SQLException { DriverManager.registerDriver(new com.mysql.jdbc.Driver()); String mysqlUrl = "jdbc:mysql://localhost/database?autoReconnect=true&useSSL=false"; Connection connection = DriverManager.getConnection(mysqlUrl, "root", "root"); return connection; }
Application.properties spring.datasource.url = jdbc:mysql:// localhost / database?autoReconnect = true&useSSL = false spring.datasource.username = root spring.datasource.password =根
Application.properties
spring.datasource.url = jdbc:mysql:// localhost / database?autoReconnect = true&useSSL = false spring.datasource.username = root
spring.datasource.password =根
请指导我如何解决这个问题。
**docker-compose.yml** version: '3' services: docker-mysql: image: mysql:5.7 environment: - MYSQL_ROOT_PASSWORD=root - MYSQL_DATABASE=database - MYSQL_USER=root - MYSQL_PASSWORD=root ports: - 3307:3306 app: image: app:latest ports: - 8091:8091 depends_on: - docker-mysql
问题是由于在jdbc url中引用了localhost引起的。
下面的配置应该可以工作。
**docker-compose.yml** version: '3' services: docker-mysql: image: mysql:5.7 environment: - MYSQL_ROOT_PASSWORD=root - MYSQL_DATABASE=database - MYSQL_USER=root - MYSQL_PASSWORD=root ports: - 3307:3306 app: image: app:latest ports: - 8091:8091 environment: SPRING_DATASOURCE_URL: jdbc:mysql://docker-mysql:3306/database?autoReconnect=true&useSSL=false depends_on: - docker-mysql