Ever needed to know whether you application is running in a container? Wrote your own code to solve this requirent in the past? Well you didn’t need to as it’s super simple out of the box!

tl;dr

It’s easy to check whether your application is running in a container by checking an environment variable through the standard .NET configuration IConfiguration constructs.

var inContainer = bool.TryParse(configuration["DOTNET_RUNNING_IN_CONTAINER"], out bool value) && value;

This line of code is trying to parse the value in the DOTNET_RUNNING_IN_CONTAINER environment variable, provided by the default configuration provider setup, and then checking the parsed value.

How does this work?

To understand how this works we need to go into the layering system of the provided Docker container images from Microsoft. The concept used in Docker images is they are built up in layers with dependencies, values being set, constructs being put in place etc. for the next layer to use.

If we hunt down far enough through the image hierarchy, starting from the ASP.NET Core base image, we will eventually get down to the runtime-deps, or run time dependencies, image. This base image (or similar) is used as the base for a lot of the Microsoft images. There are different varieties of base image due to runtime version, base OS, chiselled or not etc.

In this runtime dependencies image it sets a number of environment variables. In this new chiseled image it sets the non-root user “app” id, the default port nmber for ASPNETCORE Http end points and the DOTNET_RUNNING_IN_CONTAINER value. This environment variable being set literally has the comment above it which says “# Enable detection of running in a container”. This allows for the application running inside of this environment to determine that it is in a container.

Conclusion

In this article we have seen how we can use a built in environment variable to check whether our application is running in a container environment or not without the need to roll a bespoke custom solution. This can allow your application to work differently depending on how it is being deployed which can be powerful.

Reference