首页 > 解决方案 > Dockerizing .NET Core Web API

问题描述

我第一次尝试 dockerize .NET Core 2.x Web api 应用程序。这是我的文件:

Dockerfile

FROM mcr.microsoft.com/dotnet/core/sdk:2.1 AS build-env

WORKDIR /app

COPY *.csproj ./
RUN dotnet restore

COPY . ./
RUN dotnet publish -c Release -o out
RUN dotnet ef database update

FROM mcr.microsoft.com/dotnet/core/aspnet:2.1
WORKDIR /app
COPY --from=build-env /app/out .
ENTRYPOINT ["dotnet", "docker-webapi.dll"]

码头工人-compose.yml

version: "3.7"

# define all containers we want to use
services:
  db:
    image: mcr.microsoft.com/mssql/server:2017-latest
    # define the credentials to be used in our web application
    environment: 
        ACCEPT_EULA: 'Y'
        SA_PASSWORD: 'sa12345$'
    ports:
        - '1433:1433'
  web:
    build:
        context: .
        dockerfile: Dockerfile
    image: docker-webapi
    depends_on: 
        - db
    ports:
        - '3000:3000'

应用设置.json

{
    "ConnectionStrings": {
        "DefaultConnection": "User ID=sa;password=sa12345$;server=db;Database=master"
    },
    "Logging": {
        "LogLevel": {
            "Default": "Warning"
        }
    },
    "AllowedHosts": "*"
}

来自 Startup.cs

public void ConfigureServices(IServiceCollection services)
{
        services.AddDbContext<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        services.AddScoped<IEmployeeService, EmployeeService>();
}

每当我尝试构建时,使用以下任何命令:

docker-compose build .
or
docker build -t docker-webapi .

我得到错误:

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: 35 - An internal exception was caught) ---> 
System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (00000005, 6): No such device or address

我在这里做错了什么?

标签: dockerasp.net-web-api.net-core

解决方案


推荐阅读