gpt4 book ai didi

sql-server - .NET Core API 无法通过 docker-compose 连接到数据库

转载 作者:行者123 更新时间:2023-12-03 17:09:25 25 4
gpt4 key购买 nike

我正在使用 MSSQL Server 数据库开发 .NET 核心 Web API。我尝试将其容器化到 Docker 容器中,并使用 Docker Compose 来启动此服务。但是我的 API 无法连接到数据库。

出现以下错误:

Application startup exception: System.Data.SqlClient.SqlException (0x80131904): 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)



我的启动中的代码:
services.AddDbContext<ProductServiceDbContext>(options =>
options.UseSqlServer("server=sqlserver;port=1433;user id=sa;password=docker123!;database=ProductService;"));

Dockerfile:
FROM microsoft/dotnet:2.1-sdk AS build
WORKDIR /app

COPY *.csproj ./
RUN dotnet restore dockerapi.csproj

COPY . ./
RUN dotnet publish dockerapi.csproj -c Release -o out

FROM microsoft/dotnet:2.1-aspnetcore-runtime AS runtime

WORKDIR /app

COPY --from=build /app/out .

ENTRYPOINT ["dotnet", "dockerapi.dll"]`

Docker-撰写:
version: '3.4'

services:
productservice:
image: productservice/api
container_name: productservice_api
build:
context: ./ProductService/ProductService
depends_on:
- sqlserver
ports:
- "5000:80"

sqlserver:
image: microsoft/mssql-server-linux:latest
container_name: sqlserver
ports:
- "1433"
environment:
- ACCEPT_EULA=Y
- SA_PASSWORD=docker123!

我尝试了几件事:
  • 在 docker-compose 文件中添加链接(productservice 中的 sqlserver)
  • 将网络添加到 docker-compose 文件
  • 将连接字符串更改为
    “服务器=sqlserver;用户ID=sa;密码=docker123!;数据库=ProductService;”或“服务器=sqlserver,1433;用户ID=sa;密码=docker123!;数据库=ProductService;”
  • 最佳答案

    嘿,我遇到了类似的问题,偶然发现了您的帖子,这与我遇到的问题不同,但我想我知道您遇到的问题(抱歉回复太晚了)

    查看您的连接字符串 server=sqlserver;port=1433;user id=sa;password=docker123!;database=ProductService; ,您实际上必须以另一种方式指定端口:server=sqlserver,1433;user id=sa;password=docker123!;database=ProductService;
    希望这可以帮助!

    关于sql-server - .NET Core API 无法通过 docker-compose 连接到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54722477/

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