Currently I am facing the following challenge:
I am extending a base image, which sets a USER "safeuser" at the end. In my dependent image I try to make some changes to the filesystem of the baseimage, but since "safeuser" can't modify files from "root" I would need to change via USER ROOT, do my changes and then go back to USER SAFEUSER.
This approach does seem quite ugly, what if for example the baseimage changes the username from "safuser" to "othername"? Is there any way I can change the USER only during the build process, or RUN single commands as a different user without having to explicitly switch back to the original user? Or can I at least store some reference to the original USER during the build process somehow?
Or can I at least store some reference to the original USER during the build process somehow?
Yes, with an ENV variable from the parent image, as discussed here: Store and Restore Inherited Dockerfile USER setting
From the Dockerfile reference documentation:
A stage inherits any environment variables that were set using ENV by its parent stage or any ancestor. Refer here for more on multi-staged builds.
Parent Image:
ENV unprivilegeduser=safeuser
RUN groupadd -r unprivileged && useradd --no-log-init -r -g unprivileged $unprivilegeduser
USER $unprivilegeduser
Dependent image:
#Switch to root for a single RUN command
USER root
RUN doRootStuff
USER $unprivilegeduser
It needs three lines instead of a single, elegant "RUNAS" command that you wanted, but it is far cleaner than other alternatives like sudo and docker inspect ContainerConfig.User etc.
As per the Dockerfile guidance:
Avoid installing or using sudo as it has unpredictable TTY and signal-forwarding behavior that can cause problems. If you absolutely need functionality similar to sudo, such as initializing the daemon as root but running it as non-root, consider using “gosu”.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With