Skip to content

Instantly share code, notes, and snippets.

@MaxPeal
Forked from avishayp/Dockerfile
Last active February 24, 2022 10:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MaxPeal/64495e135a4197332783a4991669df16 to your computer and use it in GitHub Desktop.
Save MaxPeal/64495e135a4197332783a4991669df16 to your computer and use it in GitHub Desktop.
Add non-root user for alpine linux
# non root user example for alpine
#
# usage:
# $ docker build --build-arg "USER=someuser" --tag test .
# $ docker run --rm test
# or
# docker run --user default --rm -it alpine:latest
# docker run --user nobody --rm -it alpine:latest
FROM alpine
#ARG USER=default
ARG USER=user
ARG PASSWORD=pw
ENV HOME /home/$USER
# install sudo as root
RUN apk add --no-cache --update sudo
# add new user
### RUN adduser -D $USER \
### && echo "$USER ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/$USER \
### && chmod 0440 /etc/sudoers.d/$USER
RUN (
cat <<'EOF'
#!/bin/bash
echo "This is a generated shell script."
# Note that since we are inside a subshell,
#+ we can't access variables in the "outside" script.
echo "Generated file will be named: $OUTFILE"
# Above line will not work as normally expected
#+ because parameter expansion has been disabled.
# Instead, the result is literal output.
a=7
b=3
let "c = $a * $b"
echo "c = $c"
exit 0
EOF
) > /etc/profile.d/color_prompt_inc_uid-foo.sh
NORMAL="\[\e[0m\]"
RED="\[\e[1;31m\]"
GREEN="\[\e[1;32m\]"
if [ "$USER" = root ]; then
PS1="$RED\h [$NORMAL\w$RED]# $NORMAL"
else
PS1="$GREEN\h [$NORMAL\w$GREEN]\$ $NORMAL"
fi
>> /etc/profile.d/color_prompt_inc_uid.sh
RUN adduser -D $USER \
&& echo "$USER:$PASSWORD" | chpasswd \
&& echo "$USER ALL=(ALL) PASSWD: ALL" > /etc/sudoers.d/$USER \
&& echo "Defaults timestamp_timeout=30 # timestamp_timeout # After authenticating, this is the amount of time after which sudo will prompt for a password again in the same terminal" >> /etc/sudoers.d/$USER \
&& chmod 0440 /etc/sudoers.d/$USER
USER $USER
WORKDIR $HOME
# files in /home/$USER to be owned by $USER
# docker has --chown flag for COPY, but it does not expand ENV so we fallback to:
# COPY src src
# RUN sudo chown -R $USER:$USER $HOME
# CMD echo "User $(whoami) running from $PWD with premissions: $(sudo -l)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment