使用Entity Framework和Docker时无法连接MySQL主机的问题
Docker容器化ASP.NET Core 6 Web API与MySQL的EF迁移问题
环境配置
我将ASP.NET Core 6.0 Web API和MySQL数据库都进行了容器化,两者通过同一网桥网络连接,docker-compose.yml配置如下:
version: '3.4' networks: backend: services: mysqldb: container_name: community-db image: mysql:8.0 ports: - 8003:3306 environment: - MYSQL_DATABASE=dbissues - MYSQL_ROOT_PASSWORD=**** volumes: - ./mysql-data:/var/lib/mysql networks: - backend communitycare: container_name: community-care-app image: ${DOCKER_REGISTRY-}communitycare build: context: . dockerfile: CommunityCare/Dockerfile ports: - 8001:80 depends_on: - mysqldb environment: - DB_HOST=mysqldb - DB_NAME=dbissues - DB_ROOT_PASSWORD=**** networks: - backend
ASP.NET Core应用内使用以下连接字符串可正常通过Swagger和登录API连接数据库:
"DefaultConnection": "Server=mysqldb;Port=3306;Database=dbissues;User=root;Password=****;"
核心问题1:连接字符串的矛盾现象
- 用上述
Server=mysqldb;Port=3306的连接字符串执行Entity Framework迁移时,报错:Unable to connect to any of the specified MySQL hosts - 若改为使用本地映射端口的连接字符串:
迁移可正常执行,但容器内的API无法再连接数据库,只能用"DefaultConnection": "Server=localhost;Port=8003;Database=dbissues;User=root;Password=****;"mysqldb:3306的连接字符串才能正常工作。
请问这种情况是否正常?使用Docker时必须维护两套连接字符串,分别用于本地迁移和容器内API连接吗?
核心问题2:迁移时表已存在的异常
使用localhost:8003的连接字符串执行dotnet ef database update时,会提示表已存在。即便我通过MySQL Workbench删除了整个数据库模式,重新执行迁移仍会出现相同错误。
请问这是正常现象吗?Docker Compose是否会在启动服务时自动创建表,不需要手动应用迁移?
其他尝试的失败情况
- 尝试指定连接字符串执行迁移:
dotnet ef database update --connection "Server=mysqldb;Port=8003;Database=dbissues;User=root;Password=****;",仍报错Unable to connect to any of the specified MySQL hosts - 尝试在应用内自动执行迁移,即便刚删除数据库模式,仍会报错。
内容的提问来源于stack exchange,提问作者Akshay H
相关产品推荐
相关产品推荐

