How to read environment variable in ASP.NET Core 2.0 + Docker?

I have an ASP.NET core 2.0 webAPI and using the Mysql database. Therefore, I configure "ConnectionString" in the application.json file. When I run it locally, I can read the connection string and the application works fine. But I'm trying to deploy a docker using the Docker toolbox. I wrote three files: -

  • Dockerfile
  • DOckerComposer
  • Proxy.conf

I use the docker linker file because I need to run on ngnix server.I can create an image as well as run it. Now I am trying to overwrite the connection string from the docker-compose file, but it does not overwrite it.

Dockerfile

FROM microsoft/aspnetcore:2.0
ARG source
WORKDIR /app
COPY $source .
EXPOSE 5000
ENTRYPOINT ["dotnet", "xx.dll"]

Docker-compose.yaml

version: '2'
services:
    app:
        container_name: cp-api
        build: .
        environment:
        - "ConnectionStrings:Test=server=192.168.99.101; port=3306; user=root; password=X123; database=TestDb; TreatTinyAsBoolean=true;"
    rev-proxy:
        container_name: rev-proxy
        image: nginx
        ports:
         - "9090:8080"
        volumes:
         - ./proxy.conf:/etc/nginx/conf.d/default.conf`

Proxy.conf

server {
    listen 8080;

    location / {
      proxy_pass http://cp-api:5000;
    }
}

appsetting.json: -

{
  "ConnectionStrings": {
    "EcallDbNextGen": "server =192.168.99.100; port =3306; user =root; password =xxx; database =Testdb; TreatTinyAsBoolean=true;"
  },
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    }
  }
}

Startup.cs

public Startup(IConfiguration configuration,ILoggerFactory loggerFactory)
        {
            Configuration = configuration;
            loggerFactory.AddConsole(Configuration.GetSection("Logging")); //log levels set in your configuration
            loggerFactory.AddDebug(); //does all log levels
                                      //removed rest of code
        }

        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)
        {

            var connection = Configuration.GetConnectionString("EcallDbNextGen");
            services.AddDbContext<ecallnextgendbContext>(options => options.UseMySql(connection));
}
+4

Source: https://habr.com/ru/post/1686110/


All Articles