0

I have a .NET Core Console App. This console app loads a connection string stored in an environment variable. I'm retrieving that connection string using this code:

var connectionString = Environment.GetEnvironmentVariable("connection_string");

The line above works if I run the Console App by just pushing "play" in Visual Studio. However, if I run this Console App in a Docker container, the connectionString is empty. I assume it's because the connection_string environment variable is not in the Docker environment. However, I can't figure out how to add/set an environment variable in a Docker container.

For my last attempt, I added the following in my Dockerfile:

ENV connection_string <my_connection_string_value>

However, that didn't seem to matter. What am I missing?

3
  • Is there a reason you aren't using an app settings file for that? Commented Aug 10, 2018 at 22:51
  • 1
    Yes. I don't want the connection string floating around in source control, dev machines, etc. That's why I want to pull from an Environment variable. Commented Aug 11, 2018 at 1:07
  • Ok if you get it working I'll check it out, if not encrypt it. Commented Aug 11, 2018 at 3:25

2 Answers 2

2

You should be able to easily reference environment variables via the configuration builder.

var configuration = new ConfigurationBuilder()
  .AddJsonFile("appsettings.json")
  //...
  .AddEnvironmentVariables()
  .Build();

The reference use IConfiguration via DI.

private readonly IConfiguration _configuration;

public ClassConstructor(IConfiguration configuration)
{
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));

var connectionString = _configuration.GetValue("connection_string");
}

Sign up to request clarification or add additional context in comments.

Comments

1

The accepted answer assumes a ASP.NET Core environment using the configuration environment. In a pure console app, however, it's fine to just use Environment.GetEnvironmentVariable.

This seems not to read the environment variables defined in either Dockerfile or provided as parameter -e.

The variables defined that way are handed over in the current process. And this is not the default behavior. Hence, the following access will work:

Environment.GetEnvironmentVariable("VAR_NAME", EnvironmentVariableTarget.Process)

The key is the second parameter EnvironmentVariableTarget.Process.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.