System.ArgumentNullException:值不能为null。 (参数'connectionString')asp.net Core Docker-compose

时间:2020-05-16 08:08:27

标签: c# mysql docker asp.net-core docker-compose

我有一个dockerized asp.net Core应用程序,试图连接到mySql数据库。两者都在docker-compose内部运行。当我在不使用Docker的情况下测试与本地数据库的连接时,我的代码运行良好,但是当我将其部署在docker-compose内的Vm上并且调用了我的一个控制器时,出现此错误: System.ArgumentNullException :值不能为null。 (参数“ connectionString”)。 这是我的docker-compose:

version: '3'
services:
  dbgil:
   container_name: dbgil
   image: mysql
   restart: always
   ports:
     - 3306:3306
   environment:
     MYSQL_ROOT_PASSWORD: root
   volumes:
     - dbdata:/var/lib/mysql
  webserver:
    depends_on:
      - dbgil
    image: lionelquirynen/gillesquirynensys:latest
    ports:
      - "8021:80"
    links:
      - dbgil
volumes:
    dbdata:

这是我在asp.net核心应用程序中的启动:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GillesQuirynenSys.Data;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace GillesQuirynenSys
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddDbContext<MySqlDbContext>(options =>
                options.UseMySql("server=localhost;port=3306;database=test;user=root;password=root;convert zero datetime=True"));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, MySqlDbContext context)
        {
            context.Database.EnsureCreated();
            var databaseCreator = context.GetService<IRelationalDatabaseCreator>();
            databaseCreator.CreateTables();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}


我首先在我的appsettings.json文件中有连接字符串,但遇到了同样的错误,因此我尝试对其进行硬编码,但它没有任何改变。有任何想法吗?看来我的配置工作正常(至少,它在本地没有Docker)。

PS:这是我的asp.net Core应用程序的DockerFile,然后将其推送到DockerHub:

#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.

FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base
WORKDIR /app
EXPOSE 80

FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build
WORKDIR /src
COPY ["GillesQuirynenSys/GillesQuirynenSys.csproj", "GillesQuirynenSys/"]
RUN dotnet restore "GillesQuirynenSys/GillesQuirynenSys.csproj"
COPY . .
WORKDIR "/src/GillesQuirynenSys"
RUN dotnet build "GillesQuirynenSys.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "GillesQuirynenSys.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "GillesQuirynenSys.dll"]

1 个答案:

答案 0 :(得分:1)

很高兴我的回答有所帮助。 因此,基本上在docker容器中,MySQL db的服务器名称与docker-compose.yml文件中声明的服务名称相同。

还要注意您的代码: 代替这个:

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddDbContext<MySqlDbContext>(options =>
                options.UseMySql("server=localhost;port=3306;database=test;user=root;password=root;convert zero datetime=True"));
        }

->您在其中硬编码连接字符串

尝试一下:

      public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddDbContext<MySqlDbContext>(options =>
                options.UseMySql(Configuration.GetConnectionString("DefaultConnection")));
        }

并调整您的appsettings.json文件-对于生产(docker容器)构建,您将具有:

{
  "ConnectionStrings": {
    "DefaultConnection": "server=dbgil;port=3306;database=test;user=root;password=root;convert zero datetime=True"
  }
...
}

appsettings.Development.json中,您将有一个Development模式(您的本地主机)的连接字符串:

{
  "ConnectionStrings": {
    "DefaultConnection": "server=localhost;port=3306;database=test;user=root;password=root;convert zero datetime=True"
  }
...
}