Setting USER after CMD


The USER instruction sets the user name or UID to use when running the image and for any RUN, CMD and ENTRYPOINT instructions that follow it in the Dockerfile.

I want CMD to be run as root, but the image to be run as a non privileged user. If running docker exec I should get a non privileged prompt. The dockerfile reference clearly says that the USER instruction sets the user for any CMD that follows it. But when I set USER after CMD, the command is run as USER although it should be run as root. Is the information in dockerfile reference not correct? Isn’t it possible to set USER after CMD?

1 Like

Hi Henrik,

Were you able to achieve this? I am also facing similar issue.

How to use USER after CMD?



Yes and no. There is no easy way to achieve this but it is possible using sudo. I’ve actually created an Alpine base image for this (with a few extra security enhancements).

Basic usage example:

Put commands that should be run as root (before switching user) in ./rootfs/start/stage3. Then create ./Dockerfile with following contents:

FROM huggla/alpine-slim:20180927-edge as stage1

ARG APKS="<add package with executable here>"

COPY ./rootfs /rootfs

RUN apk --no-cache add $APKS \
 && apk --no-cache --quiet info > /apks.list \
 && apk --no-cache --quiet manifest $(cat /apks.list) awk -F " " '{print $2;}' > /apks_files.list \
 && tar -cvp -f /apks_files.tar -T /apks_files.list -C / \
 && tar -xvp -f /apks_files.tar -C /rootfs/ \
 && mkdir -p /rootfs/usr/local/bin \
 && cp -a <executable> /rootfs/usr/local/bin/

FROM huggla/base:20180927-edge

ENV VAR_LINUX_USER="<Linux user to run final command>" \
    VAR_FINAL_COMMAND="<command for running executable>"