简体   繁体   English

微服务无法连接到数据库

[英]Microservice cannot connect to database

I'm trying to learn microservices with docker and have a lot of trouble with that. 我正在尝试与docker学习微服务,并为此遇到很多麻烦。
docker-compose: 泊坞窗 - 撰写:

version: "3.2"

networks:
   frontend:
   backend:

services:
   catalog:
      build:
         context: .\src\Services\ProductCatalogApi
         dockerfile: Dockerfile
      image: microservices-v1.0.0
      environment:
         - DatabaseServer=mssqlserver
         - DatabaseName=CatalogDb
         - DatabaseUser=sa
         - DatabaseUserPassword=ProductApi(!)
      container_name: catalogapi
      ports:
         - "5000:80"
      networks:
         - backend
         - frontend
      depends_on:
         - mssqlserver

   mssqlserver:
      image: "microsoft/mssql-server-linux:latest"
      ports:
         - "2200:1433"
      container_name: mssqlcontainer
      environment:
         - ACCEPT_EULA=Y
         - SA_PASSWORD=ProductApi(!)
      networks:
         - backend

Dockerfile in my API: 我的API中的Dockerfile:

FROM microsoft/aspnetcore-build:2.0.0 AS build

WORKDIR /code

COPY . .

RUN dotnet restore

RUN dotnet publish --output /out/ --configuration Release 

FROM microsoft/aspnetcore:2.0.0

COPY --from=build /out /app/

WORKDIR  /app

ENTRYPOINT ["dotnet","ProductCatalogApi.dll"]

And here my problems: 这是我的问题:

  1. I don't have an access to my API. 我无权访问我的API。 I can't connect with: localhost:5000/swagger while running this with IIServer works well. 我无法与以下主机建立连接:localhost:5000 / swagger与IIServer一起运行时效果很好。

Here is my Program.cs and Startup.cs: 这是我的Program.cs和Startup.cs:

    var host = CreateWebHostBuilder(args).Build();

    using(var scope = host.Services.CreateScope())
    {
        var services = scope.ServiceProvider;
        try
        {
            var context = services.GetRequiredService<CatalogContext>();
            //context.Database.Migrate();
            CatalogSeed.SeedAsync(context).Wait();
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.Message);
            //var logger = services.GetRequiredService<ILogger>();
            //logger.LogError(ex, "An error occured while seeding database");
        }
    }
    host.Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>();

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ProductCatalogApi.Data;
using Swashbuckle.AspNetCore.Swagger;

namespace ProductCatalogApi
{
    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.Configure<CatalogSettings>(Configuration);

            var server = Configuration["DatabaseServer"];
            //var server = Environment.GetEnvironmentVariable("DatabaseServer");
            var database = Configuration["DatabaseName"];
            //var database = Environment.GetEnvironmentVariable("DatabaseName");
            var user = Configuration["DatabaseUser"];
            //var user = Environment.GetEnvironmentVariable("DatabaseUser");
            var password = Configuration["DatabaseUserPassword"];
            //var password = Environment.GetEnvironmentVariable("DatabaseUserPassword");
            var connectionString = String.Format("Server={0};Database={1};User={2};Password={3};", server, database, user, password);

            services.AddDbContext<CatalogContext>(options => options.UseSqlServer(connectionString));
            services.AddMvc();

            services.AddSwaggerGen(options =>
            {
                options.DescribeAllEnumsAsStrings();
                options.SwaggerDoc("v1", new Info
                {
                    Title = "microservice - product",
                    Version = "v1",
                    Description = "Description",
                    TermsOfService = "Tersm of Service"
                });
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseSwagger()
            .UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint($"/swagger/v1/swagger.json", "ProductCatalogAPI V1");
            });

            app.UseMvc();
        }
    }
}

I can connect to the database via SSMS, so credentials are good. 我可以通过SSMS连接到数据库,因此凭据很好。 When Migrate isn't commented out It's populate my db, so my program can connect to database somehow. 当未注释掉Migrate时,它将填充我的数据库,因此我的程序可以以某种方式连接到数据库。 2) While trying to run my service I'm getting this error: 2)尝试运行我的服务时,出现此错误:

fail: Microsoft.EntityFrameworkCore.Query[10100] 失败:Microsoft.EntityFrameworkCore.Query [10100]
catalogapi | catalogapi | An exception occurred in the database while iterating 迭代时数据库中发生异常
the results of a query for context type 'ProductCatalogApi.Data.CatalogContext'. 上下文类型“ ProductCatalogApi.Data.CatalogContext”的查询结果。
catalogapi | catalogapi | System.Data.SqlClient.SqlException (0x80131904): Cannot System.Data.SqlClient.SqlException(0x80131904):无法
open database "CatalogDb" requested by the login. 登录所请求的打开数据库“ CatalogDb”。 The login failed. 登录失败。
catalogapi | catalogapi | Login failed for user 'sa'. 用户“ sa”的登录失败。

It's not always throw that exception sometimes it's just seed db (checked via mssms) but api is still not accessible. 并非总是会抛出该异常,有时它只是种子数据库(通过mssms检查),但是api仍然无法访问。 But containers are running though. 但是容器正在运行。

Here is my github where whole project is placed (not even one completed service) so you can look here: https://github.com/AGranosik/microservices-udemy-v2 这是放置整个项目的github(甚至没有一项完整的服务),因此您可以在这里查看: https : //github.com/AGranosik/microservices-udemy-v2

Line in Program.cs is a solution: Program.cs中的Line是一个解决方案:

context.Database.Migrate();

This is initialize Proper databse if it's not exists. 如果不存在,则这是初始化适当的数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM