Aaron
Aaron

Reputation: 649

ASPNETCORE_ENVIRONMENT in Docker

i have problems setting the ASPNETCORE_ENVIRONMENT variable running my project in a docker container. The problem is that the value is always set/overwritten to "Development".

I have tried setting the environment variable in my Dockerfile using

ENV ASPNETCORE_ENVIRONMENT test

also tried setting the environment variable in my docker-compose file using

environment:
      - ASPNETCORE_ENVIRONMENT=test

When I set any other environment variable it works, for example:

environment:
      - OTHER_TEST_VARIABLE=test

I assume that the value for ASPNETCORE_ENVIRONMENT variable is overwritten somewhere but I have difficulties finding out where.

I have added Docker support to an existing project and am running the project directly via Visual Studio's Docker/Docker compose option

The project runs on Asp Net Core 2.1

Thanks in advance

My launchSettings.json:

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:53183/",
      "sslPort": 0
    }
  },
  "profiles": {

    "Docker": {
      "commandName": "Docker",
      "launchBrowser": true,
      "launchUrl": "{Scheme}://localhost:{ServicePort}/api/values"
    
    }

  }
}

I also tried adding the environment variable configuration to the launchSettings.json

"Docker": {
    "commandName": "Docker",
    "launchBrowser": true,
    "launchUrl": "{Scheme}://localhost:{ServicePort}/api/values",
    "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "test"
    }
}

My Webhost:

public static IWebHost BuildWebHost(string[] args)
{
   return WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((builderContext,config) =>
        {
            config.AddEnvironmentVariables();
        })
        .ConfigureLogging((hostingContext, logging) =>
        {
            logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
            logging.AddConsole();
            logging.AddDebug();
        })
        .UseStartup<Startup>()
        .Build();
}

My docker-compose.yml

version: '3.4'

services:
  api:
    image: ${DOCKER_REGISTRY}api
    build:
      context: .
      dockerfile: API/Dockerfile
    environment:
     - ASPNETCORE_ENVIRONMENT=test 

My Dockerfile:

FROM microsoft/dotnet:2.1-aspnetcore-runtime AS base
    
WORKDIR /app
EXPOSE 80
FROM microsoft/dotnet:2.1-sdk AS build
WORKDIR /src
COPY API/API.csproj API/
RUN dotnet restore API/API.csproj
COPY . .
WORKDIR /src/API
RUN dotnet build API.csproj -c Release -o /app

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

FROM base AS final
WORKDIR /app
COPY --from=publish /app .


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

Here is a list of the environment variables in the container

C:\Users\Administrator>docker exec -ti d6 /bin/bash
root@d6f26d2ed2c3:/app# printenv
HOSTNAME=d6f26d2ed2c3
ASPNETCORE_URLS=http://+:80
test1=asdasd
test2=dasdasd
test3=dasdasd
PWD=/app
HOME=/root
NUGET_FALLBACK_PACKAGES=/root/.nuget/fallbackpackages
DOTNET_USE_POLLING_FILE_WATCHER=1
ASPNETCORE_VERSION=2.1.3
DOTNET_RUNNING_IN_CONTAINER=true
TERM=xterm
SHLVL=1
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
ASPNETCORE_ENVIRONMENT=Development
_=/usr/bin/printenv
root@d6f26d2ed2c3:/app#

Upvotes: 60

Views: 58790

Answers (9)

oceano1970526
oceano1970526

Reputation: 129

Doing docker compose down does not actually do anything to the docker images in docker images, which is what pops back again when you do docker compose up -d.

You may have to do docker rmi imageName and then do docker compose up -d for the image to build again.

Now, setting ENV ASPNETCORE_ENVIRONMENT Development or say ENV ASPNETCORE_URLS "http://0.0.0.0:6000" in the Dockerfile should work fine when you do docker compose up -d again.

PS - You should see logs like below when you run docker compose up -d meaning the image is being built.

[+] Building 12.9s (11/11) FINISHED                                                                
 => [app internal] load .dockerignore                                                         0.0s
 => => transferring context: 2B                                                               0.0s
 => [app internal] load build definition from Dockerfile                                      0.0s
 => => transferring dockerfile: 634B                                                          0.0s
 => [app internal] load metadata for mcr.microsoft.com/dotnet/sdk:2.0                         0.0s
 => [app internal] load build context                                                         0.1s
 => => transferring context: 164.84kB                                                         0.1s
 => [app build-env 1/5] FROM mcr.microsoft.com/dotnet/sdk:6.0                                 0.0s
 => CACHED [app build-env 2/5] WORKDIR /app                                                   0.0s
 => [app build-env 3/5] COPY . ./                                                             0.2s
 => [app build-env 4/5] RUN dotnet restore Strange/*.csproj                                8.7s
 => [app build-env 5/5] RUN dotnet publish -c Release -o out PerfRunner/*.csproj              3.7s
 => CACHED [app stage-1 3/3] COPY --from=build-str-env /app/out .                                 0.0s 
 => [app] exporting to image                                                                  0.0s 
 => => exporting layers                                                                       0.0s 
 => => writing image sha256:a14415b5a8738fb8e28333f23c550370662d4503d1cf7008fc2b7c0469cb09bb  0.0s 
 => => naming to docker.io/library/str-app                                             0.0s 
[+] Running 2/2                                                                                    
 ✔ Network str_default  Created                                                        0.0s 
 ✔ Container str-app-srvc     Started 

Upvotes: 0

mwilson
mwilson

Reputation: 12900

This answer isn't stated and for me, it was the main problem. Everything I had was correct with the exception of the placement of the ARG and ENV setup in my Dockerfile.

It's important to note the position in which you define your ARG and ENV in your Dockerfile. If you do them at the top of the file, or before you build the image you need, those will get erased and not be present within your final image.

Dockerfile

FROM mcr.microsoft.com/dotnet/sdk:6.0-bullseye-slim AS build-env
WORKDIR /app

##############################
#     WON'T WORK UP HERE!    #
##############################
# ARG ENVIRONMENT
# ENV ASPNETCORE_ENVIRONMENT $ENVIRONMENT

# Expose ports
EXPOSE 80
EXPOSE 443

# Copy csproj and restore as distinct layers
COPY *.csproj ./
RUN dotnet restore

# Copy everything else and build
COPY . ./
RUN dotnet publish -c Release -o out

# Build runtime image
FROM mcr.microsoft.com/dotnet/aspnet:6.0-bullseye-slim
WORKDIR /app
COPY --from=build-env /app/out .


##############################
#      WORKS DOWN HERE!      #
##############################
# Setup your variables before running.
ARG ENVIRONMENT
ENV ASPNETCORE_ENVIRONMENT $ENVIRONMENT

ENTRYPOINT ["dotnet", "my.assembly.dll"]

azure-pipeline.yaml

- task: Docker@2
  displayName: Build an image
  inputs:
    containerRegistry: 'azureContainerConnection'
    repository: 'my-repo'
    command: 'build'
    Dockerfile: '**/Dockerfile'
    tags: latest
    arguments: '--build-arg=ENVIRONMENT=Development'

code

[HttpGet]
public IActionResult HealthCheck()
{
    return Ok(_webHostEnvironment.EnvironmentName);
}

Upvotes: 9

KevinBui
KevinBui

Reputation: 1099

For who work with linux container:

ENTRYPOINT export ASPNETCORE_ENVIRONMENT=Development && exec dotnet "app.dll"

Upvotes: 0

Vulovic Vukasin
Vulovic Vukasin

Reputation: 1748

Very stupid mistake I made.

I have VS 2019 and I added Docker support to my project. So, I have a Dockerfile for my WebApi and a docker-compose file.

Basically, I tried everything that you guys said above but nothing worked for me.

What I found out is that there was a docker-compose.override.yml which was setting these env varibales. Hope this helps somebody.

Upvotes: 4

mjwrazor
mjwrazor

Reputation: 1964

I had the same problem, I use Rider, I had the environment variable only on the docker-compose file in the service environment section.

What was happening on my end was I did not have ConnectionStrings set in my appsettings.Development.json so it defaulted to the appsettings.json file's ConnectionStrings.

I after adding the proper connection string to the development json file everything worked fine with the docker-compose up command. Hope this helps someone as well.

Upvotes: 0

Bruno Zell
Bruno Zell

Reputation: 8541

Visual Studio Docker Tooling

In case you use the Docker integration for Visual Studio (debug container from within VS) you need to pay special attention to the defaults.

Default Environment Variables

When the tooling is starting the debugger with a docker run [..] command, it supplies an -e "ASPNETCORE_ENVIRONMENT=Development" argument. You can overwrite this environment variable in the Properties/launchSettings.json.

Even though I can't see it in the issued command, in my testing I experienced another default variable ASPNETCORE_URLS=http://+:80 as well.

A good starting point to read about VS Docker Tooling is this blog post and the official documentation.

.Net-Core 3.0 Generic Host

When you use the generic host in .Net-Core 3.0 you might encounter issues when you use the new generic DOTNET_ENVIRONMENT variable, since you will have two environments specified then. This can be hard to debug. So what I like to do is to unset all defaults initially and start fresh in my Properties/launchSettings.json:

{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "profiles": {
    "Docker": {
      "commandName": "Docker",
      "environmentVariables": {
        // Overwrite default VS Docker Tools environment variables first (ASPNETCORE_ENVIRONMENT=Development; ASPNETCORE_URLS=http://+:80)
        // https://www.paraesthesia.com/archive/2019/06/18/tips-on-container-tools-for-visual-studio/
        "ASPNETCORE_ENVIRONMENT": "",
        "ASPNETCORE_URLS": "",
        "DOTNET_ENVIRONMENT": "Production",
        "DOTNET_URLS": "http://+:80"
      }
    }
  }
}

Upvotes: 14

Hani Amr
Hani Amr

Reputation: 601

In the docker-compose.override.yml file, you should find something like that:

version: '3.4'

services:
  webapplication1:
    environment:
      - ASPNETCORE_ENVIRONMENT=Development # <==

Upvotes: 37

Aaron
Aaron

Reputation: 649

Thanks for your comments, I solved my issue. It was just my mistake.

My problem was that when I added Docker-Support to my project I already had a Dockerfile included in the project.

When VS generated files for Docker-support, there was a second Dockerfile created, and one of the Dockerfiles was renamed to "Dockerfile.original".

I was using the "Dockerfile" visible in the solution explorer (which was somehow mapped to the "Dockerfile.original" file in the filesystem)

It seems that in the background my changes where written to "Dockerfile.original" but this file wasn't used while docker-compose was running. It used the empty generated Dockerfile that wasn't visible in the Solution explorer.

Upvotes: 3

Edward
Edward

Reputation: 29966

It works for me by configuring ASPNETCORE_ENVIRONMENT with command dotnet CoreDocker.dll --environment="X"

Try to change dockerfile like below:

ENTRYPOINT ["dotnet", "CoreDocker.dll", "--environment=X"]

Upvotes: 51

Related Questions