Reputation: 332
I'm writing a Dockerfile for an image that, when run, performs the following two things in order:
The problem is that ENTRYPOINT
can only be run as a single user (whichever USER
is set last before ENTRYPOINT
in the Dockerfile). In this case, the ENTRYPOINT
can only run as either root or the non-root user.
I can't put CMD
commands before ENTRYPOINT
, because they just get overridden by ENTRYPOINT
.
How can I accomplish what I need?
Upvotes: 9
Views: 5662
Reputation: 1070
As alternative to @BMitch's answer, you can use another utilities like chroot
or setpriv
available in most distribution repositories.
chroot
With the --userspec=user[:group]
flag, chroot can run a process as a different user and/or with a different primary group:
$ docker run -it --rm ubuntu:trusty chroot --userspec=nobody / ps aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
nobody 1 5.0 0.0 7136 756 ? Rs+ 17:04 0:00 ps aux
setpriv
Available in newer util-linux (>= 2.32.1-0.2, in Debian; https://manpages.debian.org/buster/util-linux/setpriv.1.en.html):
$ docker run -it --rm buildpack-deps:buster-scm setpriv --reuid=nobody --regid=nogroup --init-groups ps faux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
nobody 1 5.0 0.0 9592 1252 pts/0 RNs+ 23:21 0:00 ps faux
su-exec
In the Alpine Linux ecosystem, su-exec is a minimal re-write of gosu in C, making for a much smaller binary, and is available in the main Alpine package repository.
(The above list was extracted from tianon/gosu's github repo).
Upvotes: 0
Reputation: 264036
You start your container as root. This runs your entrypoint as root. Perform all the steps you need, then make the last step look like:
exec gosu username /bin/bash
To launch /bin/bash
as the user username
. You can find gosu in this github repo. It has the advantage of running an su
command with an implicit exec which avoids leaving the parent process around which can break signal handling.
If you make /bin/bash
the value of CMD, you can make this more flexible with:
exec gosu username "$@"
Make sure to use the JSON syntax for ENTRYPOINT
and CMD
to avoid issues with the merged commands and cli args.
This is preferable over sudo
since it avoids any option to go back from the user to root.
Upvotes: 8