我正在尝试为要在docker上部署的服务设置数据库连接,该服务和数据库都在docker化。
将有效载荷发布到服务的API时,出现以下错误:
SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 40 - Could not open a connection to SQL Server)
API定义为:
[HttpPost]
public async Task<IActionResult> Postfoo([FromBody] Foo foo)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.Foos.Add(foo);
await _context.SaveChangesAsync();
return CreatedAtAction("GetFoo", new { id = foo.ID }, foo);
}
在
appsettings.json
中,数据库连接定义如下:"ConnectionStrings": {
"DefaultConnection": "Server=tcp:127.0.0.1,1433;Trusted_Connection=True;MultipleActiveResultSets=true;User ID=sa;Password=Pass@word"
},
定义数据库连接的
Startup.cs
中的启动逻辑如下: public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddDbContext<WorkflowContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
在
docker-compose.yml
中,数据库服务定义为:version: '3.4'
services:
sql.data:
image: microsoft/mssql-server-linux:2017-latest
在
docker-compose.override.yml
中,与数据库有关的部分定义为:version: '3.4'
services:
sql.data:
environment:
- SA_PASSWORD=Pass@word
- ACCEPT_EULA=Y
ports:
- "1433:1433"
我可能已经忽略了,尽管仍然看不到缺少了什么?
最佳答案
为了在两个容器之间共享网络,我们可以使用docker-compose来创建共享网络。
请按照以下步骤操作:
version: '3.4'
services:
coredocker:
image: coredocker
build:
context: .
dockerfile: CoreDocker/Dockerfile
sql.data:
image: microsoft/mssql-server-linux:2017-latest
environment:
- SA_PASSWORD=Pass@word
- ACCEPT_EULA=Y
ports:
- "1433:1433"
appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Server=sql.data,1433;Database=CoreDocker;MultipleActiveResultSets=true;User ID=sa;Password=Pass@word"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
这里有两点:
Server=tcp:127.0.0.1,1433;
更改为Server=sql.data,1433
,即服务名称和端口Trusted_Connection=True;
关于sql-server - SQL Server与Docker和Entity Framework的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57283909/