我创建了一个带有mysql数据库的容器,并且与.net
应用程序的手动连接非常有效。现在,我将使用docker-compose
自动构建mysql容器和.net
应用程序映像。
我的docker组成看起来像这样。
version: '3.1'
networks:
overlay:
services:
authentication_service:
image: authentication_service:latest
depends_on:
- "authentication_service_db"
- "adminer"
build:
context: .
dockerfile: Dockerfile
links:
- authentication_service_db
ports:
- "5003:80"
networks:
- overlay
authentication_service_db:
image: mysql:8.0.3
environment:
MYSQL_ROOT_PASSWORD: secret
MYSQL_DATABASE: authenticationdb
ports:
- 3305:3306
restart: always
volumes:
- ./data-authentication:/var/lib/mysql
networks:
- overlay
当我在开发中启动应用程序时,将打印连接字符串,其外观类似于server=localhost;Port=3305;Database=authenticationdb;Uid=root;Pwd=secret
。这行得通。
当我运行docker-compose up -d --build
时,它会更改:
server=authentication_service_db;Port=3305;Database=authenticationdb;Uid=root;Pwd=secret;
我的连接测试脚本:
private static void WaitForDbInit(string connectionString)
{
var connection = new MySqlConnection(connectionString);
Console.WriteLine("Connecting with credentials: {0}", connectionString);
var retries = 1;
while (retries < 5)
{
try
{
Console.WriteLine("Connecting to db. Trial: {0}", retries);
connection.Open();
connection.Close();
break;
}
catch (MySqlException)
{
Thread.Sleep((int) Math.Pow(2, retries) * 1000);
retries++;
}
}
}
日志:
Connecting to db. Trial: 1
Connecting to db. Trial: 2
Connecting to db. Trial: 3
Connecting to db. Trial: 4
[...]
application startup exception: MySql.Data.MySqlClient.MySqlException (0x80004005): Unable to connect to any of the specified MySQL hosts.
at MySqlConnector.Core.ServerSession.ConnectAsync(ConnectionSettings cs, ILoadBalancer loadBalancer, IOBehavior ioBehavior, CancellationToken cancellationToken) in C:\projects\mysqlconnector\src\MySqlConnector\Core\ServerSession.cs:line 299
appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"MysqlConnection": {
"connectionString": "server=authentication_service_db;Port=3305;Database=authenticationdb;Uid=root;Pwd=secret;"
}
}
所以我不知道如何调试或下一步该怎么做。使用docker compose时没有连接。
答案 0 :(得分:1)
您将端口3306映射到3305到开发应用程序的主机。因此,您可以在端口3305上连接到db。但是,您仍在使用容器内部的端口3305。由于您的服务(authentication_service_db)正在监听端口3306,而不是3305,因此您的应用程序无法连接数据库。
您必须更改连接字符串以使用端口3306,而不是3305。