gpt4 book ai didi

mysql - Spring Boot + MySQL + Docker Compose - 无法让 Spring Boot 连接到 MySQL

转载 作者:行者123 更新时间:2023-12-02 02:39:00 24 4
gpt4 key购买 nike

我一直在尝试在后端(在 Spring Boot 上运行)容器和预构建的 MySQL 容器之间建立连接。但是,我无法连接它。我的 docker compose 文件是:

version: '3.7'

services:

test-mysql:
image: mysql
restart: always
volumes:
- db_data:/var/lib/mysql
environment:
MYSQL_DATABASE: testdb
MYSQL_USER: test
MYSQL_PASSWORD: test
MYSQL_ROOT_PASSWORD: root

backend:
depends_on:
- test-mysql
build:
context: backend
dockerfile: Dockerfile
ports:
- "8080:8080"
restart: always

volumes:
db_data: {}

我的 application.properties:
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.datasource.url=jdbc:mysql://test-mysql:3306/testdb?autoReconnect=true&failOverReadOnly=false&maxReconnects=10
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=test
spring.datasource.password=test

当我使用 docker-compose up , Spring Boot 无法识别容器名称 test-mysql .它抛出: java.net.UnknownHostException
当我将其更改为 IP 时,它说连接被拒绝。我到处找,都找不到解决办法。我希望任何人都可以帮助我。谢谢!

最佳答案

您必须在 Composer 文件中提及后端 mysql 属性,如下所示,

backend:
depends_on:
- test-mysql
build:
context: backend
dockerfile: Dockerfile
ports:
- "8080:8080"
restart: always
environment:
SPRING_DATASOURCE_URL: jdbc:mysql://test-
mysql:3306/testdbautoReconnect=true&failOverReadOnly=false&maxReconnects=10
SPRING_DATASOURCE_USERNAME: test
SPRING_DATASOURCE_PASSWORD: test
links:
- test-mysql:test-mysql

如果这不起作用,请尝试创建一个通用的 docker 网络并将其添加到您的 Composer 文件中,如下所示,
backend:
depends_on:
- test-mysql
build:
context: backend
dockerfile: Dockerfile
ports:
- "8080:8080"
restart: always
environment:
SPRING_DATASOURCE_URL: jdbc:mysql://test-
mysql:3306/testdbautoReconnect=true&failOverReadOnly=false&maxReconnects=10
SPRING_DATASOURCE_USERNAME: test
SPRING_DATASOURCE_PASSWORD: test
networks:
-common-network

test-mysql:
image: mysql
restart: always
volumes:
- db_data:/var/lib/mysql
environment:
MYSQL_DATABASE: testdb
MYSQL_USER: test
MYSQL_PASSWORD: test
MYSQL_ROOT_PASSWORD: root
networks:
-common-network

#Docker Networks
networks:
common-network:
driver: bridge

#Volumes
volumes:
dbdata:
driver: local

关于mysql - Spring Boot + MySQL + Docker Compose - 无法让 Spring Boot 连接到 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60961757/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com