How to check if a Go program is running within a Docker container
Over the last couple of months I’ve been migrating a Go application into several individual Docker containers based on the functionality they provide. If the Go program is running within a Docker container, as opposed to my local development machine, I’d set-up different paths to the logging files and configuration files.
So I needed a way to detect if the running instance of a program is actually running within a container. Luckily, Docker creates a .dockerenv file within the root folder of the container. So all I needed to do was check for the existence of this file.
func (app *App) isRunningInDockerContainer() bool {
// docker creates a .dockerenv file at the root
// of the directory tree inside the container.
// if this file exists then the viewer is running
// from inside a container so return true
if _, err := os.Stat("/.dockerenv"); err == nil {
return true
}
return false
}
Above is the function I use to check if the program is running within a Docker container. I use the return value from this function along with checking if a known mount point is also accessible.