Spring Boot JDBC无法连接到Docker容器中的mysql

时间:2019-09-30 06:13:15

标签: mysql spring-boot docker jdbc

我正在尝试在两个单独的docker容器中运行spring boot应用程序(作为简单的REST api)和mysql服务器。但是,我无法在spring app中获得jdbc连接来连接到mysql。它们都是独立工作的,当我在本地运行spring boot和mysql时,实现也可以工作。

docker-compose.yml

version: '3'
services:
  database:
    image: mysql:latest
    container_name: mysqldb
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=password
    expose:
      - 3306
    ports:
      - 3306:3306
    networks:
      - backend
    volumes:
      - "dbdata:/var/lib/mysql"

  web:
    container_name: springboot
    build: .
    depends_on:
      - database
    expose:
      - 8080
    ports:
      - 8080:8080
    networks:
      - backend

networks:
  backend:

volumes:
  dbdata:

在Spring Boot应用程序中:

val dataSource = DriverManagerDataSource()
dataSource.setDriverClassName("com.mysql.jdbc.Driver")
dataSource.setUrl("jdbc:mysql://mysqldb:3306/$dbName?characterEncoding=latin1")
dataSource.username = "dev"
dataSource.password = "password"

val jdbcTemplate = JdbcTemplate(dataSource)

Spring Boot返回错误:

{
    "status": 500,
    "error": "Internal Server Error",
    "message": "Failed to obtain JDBC Connection; nested exception is com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure\n\nThe last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server."
}

我能够通过mysql cli从spring boot容器连接到mysql容器。因此,看来springboot容器能够解析“ mysqldb”。

这似乎应该很简单。我不确定错误在哪里,但我想这可能与我不熟悉的弹簧靴内部工作有关。

1 个答案:

答案 0 :(得分:2)

将此dataSource.setUrl("jdbc:mysql://mysqldb:3306/$dbName")更改为:

dataSource.setUrl("jdbc:mysql://database:3306/$dbName")

您在compose中的服务名称为database,因此您需要使用它