Microservice cannot connect to database

0

I'm trying to learn microservices with docker and have a lot of trouble with that.
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:

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. I can't connect with: localhost:5000/swagger while running this with IIServer works well.

Here is my Program.cs and 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. When Migrate isn't commented out It's populate my db, so my program can connect to database somehow. 2) While trying to run my service I'm getting this error:

fail: Microsoft.EntityFrameworkCore.Query[10100]
catalogapi | An exception occurred in the database while iterating
the results of a query for context type 'ProductCatalogApi.Data.CatalogContext'.
catalogapi | System.Data.SqlClient.SqlException (0x80131904): Cannot
open database "CatalogDb" requested by the login. The login failed.
catalogapi | Login failed for user 'sa'.

It's not always throw that exception sometimes it's just seed db (checked via mssms) but api is still not accessible. 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

asp.net
sql-server
docker
docker-compose
asked on Stack Overflow Jul 30, 2019 by Kenik • edited Jul 30, 2019 by Kenik

1 Answer

1

Line in Program.cs is a solution:

context.Database.Migrate();

This is initialize Proper databse if it's not exists.

answered on Stack Overflow Jul 31, 2019 by Kenik

User contributions licensed under CC BY-SA 3.0