【发布时间】:2020-12-11 04:21:42
【问题描述】:
作为参考,我尝试了以下链接中的想法无济于事:
Docker-Compose Unable to connect to any of the specified MySQL hosts Connect to MySQL container from Web Api .Net Core Container? How to get Ip Address?
我有三个容器化应用程序:mysql@8.0“暴露”——因为没有更好的术语——在端口 9999 后面; .NET Core 3.1 WebAPI;和一个容器化的 Angular 应用程序。 Angular 应用程序可以成功地调用 5001 端口后面的 WebAPI。问题似乎是 Web API 与 MySQL 容器建立了连接。
所有应用程序都作为容器部署在我的本地开发工作站上。 Web API 和 MySQL 数据库正在使用一个 docker-compose.yml 进行部署,我在下面分享了它。我为前端应用构建了一个简单的镜像,并从 Docker 命令行进行部署。
这是我的docker-compose.yml API 和 DB:
version: "3.3"
services: # list of services composing your application
db: # the service hosting your MySQL instance
image: mysql:8.0 # the image and tag docker will pull from docker hub
volumes: # this section allows you to configure persistence within multiple restarts
- db_data:/var/lib/mysql
restart: always # if the db crash somehow, restart it
ports:
- "9999:3306"
environment: # env variables, you usually set this to override existing ones
MYSQL_ROOT_PASSWORD: *****
networks:
- soar-network
soar-api: # you application service
build: ./ # this tells docker-compose to not pull from docker hub, but to build from the Dockerfile it will find in ./
restart: always
ports:
- "5001:80"
networks:
- soar-network
# set a dependency between your service and the database:
# this means that your application will not run if the db service is not running,
# but it doesn't assure you that the dabase will be ready to accept incoming connection
# (so your application could crash untill the db initializes itself)
depends_on:
- db
volumes:
db_data: # this tells docker-compose to save your data in a generic docker volume. You can see existing volumes typing 'docker volume ls'
networks:
soar-network:
driver: bridge
Web API 代码对我在代码中使用的DbContext 使用以下连接字符串:
"ConnectionStrings": {
"DefaultConnection": "server=localhost;port=9999;uid=root;pwd=*****;database=SoarDb"
}
请注意,连接字符串中的port 与我在docker-compose 中映射的内容相匹配。我已经尝试过使用3306 和33060,也无济于事。
我也尝试过使用127.0.0.1 作为server 值,但没有成功。
Web API 容器中记录的错误如下:
soar-api_1 | fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]
soar-api_1 | An error occurred using the connection to database 'SoarDb' on server 'localhost'.
soar-api_1 | fail: Microsoft.EntityFrameworkCore.Query[10100]
soar-api_1 | An exception occurred while iterating over the results of a query for context type 'DataAccess.SoarDataContext'.
soar-api_1 | MySql.Data.MySqlClient.MySqlException (0x80004005): Unable to connect to any of the specified MySQL hosts.
soar-api_1 | at MySqlConnector.Core.ServerSession.ConnectAsync(ConnectionSettings cs, ILoadBalancer loadBalancer, IOBehavior ioBehavior, CancellationToken cancellationToken) in C:\projects\mysqlconnector\src\MySqlConnector\Core\ServerSession.cs:line 442
另一个奇怪的事情是:我可以添加迁移并使用dotnet-ef add migration 和dotnet-ef database update 将数据库更新到这个特定的容器化数据库。
非常感谢任何见解。我尝试了许多不同的设置排列和调整,但没有运气,不知道我在误解什么。
【问题讨论】:
标签: c# mysql docker .net-core docker-compose