Spring boot JDBC无法连接到docker容器中的mysql

cdubbs85

我正在尝试在两个单独的 docker 容器中运行 Spring Boot 应用程序(作为一个简单的 REST api)和 mysql 服务器。但是,我无法在 spring 应用程序中获取 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 启动返回的错误:

{
    "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”。

这看起来应该很简单。我不确定错误在哪里,但我猜它与我不熟悉的弹簧靴内部工作原理有关。

林派

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

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

您的服务名称composedatabase,因此您需要使用它

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Docker:无法连接Spring Boot和MYSQL

Docker中的Postgres Server无法连接到Spring Boot应用程序

无法从容器外部运行的Spring Boot应用程序连接到容器中运行的Kafka

难以将Mysql连接到Spring Boot

docker容器中的Spring服务无法连接到docker容器中的mysql

Docker MySQL-无法从Spring Boot应用连接到MySQL数据库

Spring Boot无法连接到MySql

无法将mysql连接到Spring Boot项目

Angular无法连接到Docker Compose中的Spring Boot终结点

Spring Boot连接到MySQL docker

Spring Boot容器无法连接到Kafka容器

无法从Spring Boot连接到Dockerized Redis

无法访问Docker容器中的Spring Boot API

无法从Spring Boot连接到Rabbitmq STOMP

在不同的Docker容器中运行的Spring Boot应用拒绝连接

无法从Spring Boot Docker容器连接到本地MySQL数据库服务器

Spring Boot App容器无法连接到MySQl容器

为什么我不能通过Docker-compose将spring-boot容器连接到mysql sql容器?

即使提供正确的mysql服务名称,Spring-boot也无法连接到mysql容器

在Spring Boot(Cloud App)中无法连接到Oracle DB

从Spring Boot连接到内存中的ElasticSearch

在Docker容器中运行Spring Boot应用程序,无法连接MySQL

将 Spring Boot Docker 容器连接到 MongoDB Docker 容器

是否可以将非容器化的 Spring Boot 应用程序连接到 MongoDB Docker 容器?

Spring Boot 无法连接到 docker 容器内运行的 rabbitmq ..而从浏览器中我可以访问 rabbitmq 控制台

Spring Boot 无法连接到 MySQL 容器

spring boot 应用程序未连接到在 docker 容器中运行的 activemq

Spring Boot 应用程序无法连接到 Docker 中的 Redis 副本

Spring Boot + MySQL docker 容器