Skip to content

Instantly share code, notes, and snippets.

@amacneil
Created September 4, 2020 23:30
Show Gist options
  • Save amacneil/056dcc97552dc0878683d4bd23358567 to your computer and use it in GitHub Desktop.
Save amacneil/056dcc97552dc0878683d4bd23358567 to your computer and use it in GitHub Desktop.
Unprivileged user in docker
FROM ubuntu
# install apt packages
RUN apt-get update \
&& apt-get install -qq --no-install-recommends \
gosu \
man \
sudo \
&& rm -rf /var/lib/apt/lists/*
# create user with sudo privileges
RUN useradd -m ubuntu \
&& echo "ubuntu ALL=(ALL) NOPASSWD: ALL" | tee /etc/sudoers.d/ubuntu \
&& mkdir -p -m 700 /home/ubuntu/.ssh \
&& echo "Host *\n StrictHostKeyChecking no" | tee /home/ubuntu/.ssh/config \
&& chown -R ubuntu:ubuntu /home/ubuntu/.ssh
WORKDIR /home/ubuntu
# install entrypoint
COPY entrypoint.sh /
ENTRYPOINT ["/entrypoint.sh"]
CMD ["bash"]
#!/bin/bash
# docker entrypoint script
# detects UBUNTU_UID / UBUNTU_GID environment variables and updates permissions
set -eu
owner=""
# inspect environment variables
if [[ -n "${UBUNTU_UID:-}" && "${UBUNTU_UID:-}" != "1000" ]]; then
usermod -u "$UBUNTU_UID" ubuntu
owner="$UBUNTU_UID"
fi
if [[ -n "${UBUNTU_GID:-}" && "${UBUNTU_GID:-}" != "1000" ]]; then
groupmod -g "$UBUNTU_GID" ubuntu
owner="$owner:$UBUNTU_GID"
fi
if [[ -n "$owner" ]]; then
# fix ownership of home directory and hidden files
# skip non-hidden files in case they are mounted volumes
chown "$owner" /home/ubuntu
chown -R "$owner" /home/ubuntu/.*
fi
# execute command as ubuntu user
exec gosu ubuntu "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment