buildkit icon indicating copy to clipboard operation
buildkit copied to clipboard

`/.dockerenv` does not exist during build

Open Bilge opened this issue 1 year ago • 9 comments

Although containers run by Docker will inevitably have a /.dockerenv file present, images at build time do not have this file present. This causes inconsistent semantics with some tools, such as Composer, that use the presence of this file to alter their behaviour.

Bilge avatar Dec 20 '23 20:12 Bilge

There is no documentation afaik that a container should have such a file. A different method should be used for detecting a container.

tonistiigi avatar Dec 22 '23 22:12 tonistiigi

Feel free to suggest one such method.

Bilge avatar Dec 22 '23 22:12 Bilge

It depends on what it is used for. It is always better to detect the actual feature you need or what changes the behavior for your app, rather than to look for a string "docker" leaking to some file. If you are detecting a specific image then that image should define a custom env. For string-based matching /proc/1/mountinfo contains some identifiable info (there may be simpler ways).

tonistiigi avatar Dec 22 '23 23:12 tonistiigi

Clearly we are not talking about a specific image here: the image could be literally anything.

Bilge avatar Dec 22 '23 23:12 Bilge

Just FYI the reason we need to detect Docker in Composer is for usability, as we prevent/warn users when they run Composer as root usually as that is typically a bad usage pattern, but in a container that is typically done so there we do not want to warn. So having an easy and reliable way to detect that is very valuable.

Seldaek avatar Jan 04 '24 09:01 Seldaek

So having an easy and reliable way to detect that is very valuable.

If you have an ENTRYPOINT shell script and the shell's PID ($$) is 1, it is highly likely to be running inside a container.

AkihiroSuda avatar Jan 04 '24 14:01 AkihiroSuda

@AkihiroSuda thanks but not sure what the ENTRYPOINT shell script is concretely how do I detect this, is it on /ENTRYPOINT as a file? Is it a env var or something?

The shell's PID I am also not sure how I can access this from within a sub-process, as when you run Composer it runs a new PHP process and then in there I can't simply know which shell started it. I could check ps ax output and see what runs as PID 1 if it's bash or another common shell probably one could infer it's docker then and not a proper linux system which booted with init/systemd.

Seldaek avatar Jan 08 '24 10:01 Seldaek

Maybe just check that systemctl is-system-running fails?

Doesn't work for Alpine, Devuan, etc. though.

AkihiroSuda avatar Jan 08 '24 11:01 AkihiroSuda

Yeah that's the issue, there's apparently nothing simple and reliable.

Seldaek avatar Jan 08 '24 12:01 Seldaek