9

We have a .NET Core project in Visual Studio (2017) that has Docker support added. Our project relies on environment variables to configure itself at start up. As we understand it, in order to pass environment variable values to a container you specify them as arguments to the docker run command using -e.

When you run the containerized version of the project from Visual Studio by selecting the Docker profile, we noticed that Visual Studio executes a docker run command. However, we've not been able to figure out how to get Visual Studio to include our environment variable values when it runs the container.

Is there a way to tell Visual Studio to pass our environment variable values to a container it runs?

Note that we do not want to specify the environment variable values in the image since the values will change depending on where it is deployed to.

madhatter160
  • 439
  • 5
  • 13

3 Answers3

17

You can choose to include additional environment files to be passed to the docker run command by adding the following property to your .csproj file:

<DockerfileRunEnvironmentFiles>your_env_file.env</DockerfileRunEnvironmentFiles>
Hani Amr
  • 581
  • 4
  • 6
  • 3
    That worked - nice! The tag needs to go inside of a tag. That means that you can specify different .env files for Debug, Release, or another configuration. – madhatter160 Oct 04 '18 at 14:38
  • 4
    -e AWS_ACCESS_KEY_ID -e AWS_SECRET_ACCESS_KEY Worked better for me as is pushes in the host values. Two good options. For this one credit to https://stackoverflow.com/questions/54164779/docker-run-command-for-asp-net-core-and-visual-studio-2017 – KevinC Mar 15 '21 at 03:01
2

I have a command line .NET Core application that consumes a secret in the input arguments, like mycli -ACCOUNT_KEY abcdef123=. For debugging purposes, I don't want to have this value in my source countrol, so I set it as an environment variable on my system that I'm then passing in the command line arguments. This is what I did:

In the system environment variables:

enter image description here

In the project settings:

enter image description here

In the .csproj file:

enter image description here

In the .gitignore:

enter image description here

Wouter Van Ranst
  • 521
  • 4
  • 14
  • You could easily use User Secrets eg by mounting volume `-v ${APPDATA}\Microsoft\UserSecrets:/root/.microsoft/usersecrets:ro` – c-romeo Dec 14 '20 at 22:32
  • 1
    @romi - no need for this, it is done automatically by VS (see [here](https://learn.microsoft.com/en-us/visualstudio/containers/container-build?view=vs-2019#ssl-enabled-aspnet-core-apps)) – Dan Z Jun 03 '21 at 14:34
0

In case your env variable does not change frequently, you can also put them in the Docker file , during the image-building process the env variable will be assigned to the container

FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80

ENV ASPNETCORE_ENVIRONMENT=dev
Matt Qafouri
  • 1,449
  • 2
  • 12
  • 26