docker / buildx

Docker CLI plugin for extended build capabilities with BuildKit
Apache License 2.0
3.54k stars 480 forks source link

Mount a file at /.dockerenv during build, or otherwise give a way to detect buildkit environment #1447

Open ciaranmcnulty opened 1 year ago

ciaranmcnulty commented 1 year ago

Some libraries in the wild use the presence of /.dockerenv to detect if they are on a containerised environment:

https://github.com/mongodb-js/mongosh/blob/afce071bb15cc22f51c41989656603e6d1ec66dd/packages/cli-repl/src/cli-repl.ts#L167 https://github.com/woodgern/metrix/blob/d1a6c81b7110276c831323100fd834159ede0b10/Makefile#L11 https://github.com/composer/composer/blob/6c85b875f27185b0e36c35aac98af634be25bdc0/src/Composer/Util/Platform.php#L152

The specific case that composer (last link) uses it to detect WSL by checking if /proc/version contains Microsoft, but then using .dockerenv to check if we're in a 'real' linux container that is merely sharing the WSL kernel.

The .dockerenv file is provided by the classic docker build in the build environment as well, but is not provided during a buildkit build.

It'd be worth mounting an empty file there IMO, or if not it'd be good to document an official way to detect a build environment (cgroups?)

crazy-max commented 1 year ago

I don't find anything in our reference docs about this .dockerenv file. Nothing in CLI source too. There is smth in moby: https://github.com/search?q=repo%3Amoby%2Fmoby%20.dockerenv&type=code but seems to be internal. @thaJeztah Any idea?

neersighted commented 1 year ago

It's a relic of the old lxc execution driver that was preserved since some things started to depend on it for checking if they were in a container. The legacy builder does create this file; I suspect that the in-daemon buildkit driver might create it too. I suspect that the managed container driver is what doesn't create this file.

thaJeztah commented 1 year ago

I know it's been used as a bit of an undocumented hack to detect if you're in a container, but it's not a formal API. There's been some discussions in the past about exposing wether you're inside a container, and there's been some back-and-forth on that which trickled down to discussions that this should mostly be "opaque", and wether exposing this would be desirable.

ISTR some runtimes added an environment variable (CONTAINER (?)), which is used by systemd to detect if it's running inside a container. I recall there were some complaints about containerd and docker not doing this, but for that to be added, I think it should be formalised in the runtime spec (and wether it should be opt-in or "always on").