How to pass parameters to a .NET core project with dockerfile
You can do this with a combination of ENTRYPOINT
to set the command, and CMD
to set default options.
Example, for an ASP.NET Core app:
ENTRYPOINT ["dotnet", "app.dll"]
CMD ["argument"]
If you run the container with no command, it will execute this command when the container starts:
dotnet app.dll argument
And the args
array will have one entry, "argument". But you can pass a command o docker run
to override the CMD
definition:
docker run app arg1 arg2
I used environment variables which can be set by docker-compse.yml too
public static class EnvironmentHelper
{
public const string EnvironmentArguments = "DOTNETCORE_ARGUMENTS";
private static string[] _arguments;
public static string[] Arguments
{
get
{
bool argumentsExist = _arguments != null && _arguments.Any();
if (!argumentsExist)
{
IDictionary environmentVariables = Environment.GetEnvironmentVariables();
if (!environmentVariables.Contains(EnvironmentArguments))
{
throw new Exception("Environment Arguments do not exist");
}
var argumentsHolder = environmentVariables[EnvironmentArguments] as string;
const char argumentSeparator = ' ';
_arguments = argumentsHolder?.Split(argumentSeparator);
}
return _arguments;
}
}
}