Docker USER Directive

09/29/2021 docker commit is not a good way to create docker image as it makes image size bigger, using multi-stage build instead.

From major security hardening items: Try to explicitly set a USER/uid – to avoid even accidental startup as root. This is a good point I agree. But in our case it’s impossible to use USER directive with non-root user in dockerfile at beginning, as we need root user to install and configure services in containers, then alter the settings that cater to non-root user.

The solution is in the last docker commit, use --change 'USER 1000' to set default user as non-root. For example:

1
2
3
4
docker commit --change 'USER 1000' \
--change 'ENTRYPOINT ["/opt/xx/initScripts/startcontainer.sh"]' \
-c 'ENV SETUPINPROGRESS ""' \
${SERVICES_HOST} ${DOCKER_TEMPIMAGE_TAG_SERVICES}:3

Note that the non-root user must exist in image, if it belongs to multiple groups (one primary and several supplementaries), only specify id is enough.

If later we need to run as root, just specify runAsUser: 0 in K8s yaml or --user 0 in docker run command, it will overwrite the default setting.

You can use docker inspect to check default USER:

1
docker inspect <image>:<tag> | grep -i user
0%