From 3f05078fd1afc133a2e2007c8a2bf50fbafabc84 Mon Sep 17 00:00:00 2001 From: Willy Tarreau Date: Sun, 26 Oct 2025 22:47:01 +0100 Subject: preinit: detect when run inside a container PID 2 is always assigned to kthreadd since kernel 2.6+ and to keventd in 2.4, and is always present. The only case where it's not there is in a container. Thus by checking the presence of /proc/2/status we can reliably detect the presence of a container and decide whether or not to populate /dev, and if we want to execute init or not. Indeed, inside a container, init cannot do everything and will be limited. Here instead, we'll just run rc.S and rc.M, then wait for a shutdown signal via the "ws" command of latest init code. Doing this in the regular init allows to sensibly simplify image management in multiple environments because the rest is only a matter of service configuration. Note that as an alternative to checking /proc/2/status, we could also rely on the presence of /.dockerenv which is set by docker, but this might differ in other environments and could possibly also appear by accident (touch) on R/W filesystems. Since /proc is expected to always be there during boot, checking pid 2 seems more reliable. --- .preinit | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/.preinit b/.preinit index 4f4ef65..165a8b9 100644 --- a/.preinit +++ b/.preinit @@ -25,11 +25,10 @@ st /var/. md /var/tmp 1777 md /var/run 755 -# only populate /dev if we don't have a devtmpfs. Older versions don't -# have the test so we pre-set the return code with a failure using the -# eq test. -eq 0 1 +# only populate /dev if we don't have a devtmpfs and we're not in a container. +# PID 2 (kthreadd/keventd) is always present natively, not in containers. td +|!st /proc/2/status |{ md /dev/pts 755 bl 0600 0 0 3 0 hd[c,ab,64][I,0-16,1] @@ -130,3 +129,11 @@ rf /proc /proc/sys/kernel/random/boot_id /proc/self/maps /proc/net/dev /sys/firm in /sbin/init-sysv +st /proc/2/status +|{ + # start the services manually in a container + /sbin/rc.S + /sbin/rc.M + # and wait for SIGINT/SIGTERM/halt/reboot + ws +} -- 2.17.5