Skip to content

Instantly share code, notes, and snippets.

@pkubik
Created April 28, 2023 10:42
Show Gist options
  • Save pkubik/4f93183f7abe41d1c16590beb1369a81 to your computer and use it in GitHub Desktop.
Save pkubik/4f93183f7abe41d1c16590beb1369a81 to your computer and use it in GitHub Desktop.
An entrypoint that sets umask before running user script

Entrypoint for docker with host dir mountpoint

The idea is to use this along with -v $PWD:/app option.

Whenever you use this workflow all files created in your working directory will be created by the docker user (e.g. root) requiring you to use sudo for clean-up...

... random sudo rm -rf something is just what you need in your life.

To avoid this issue add one of the following bash scripts as your entrypoint like this (in Dockerfile):

COPY user_shell.sh /usr/bin/user_shell
RUN chmod +x /usr/bin/user_shell
ENTRYPOINT [ "/usr/bin/user_shell" ]

Which one to choose?

The first script umask_shell.sh is a simpler alternative that simply sets umask 0000 before running your desired command.

Almost all files created with your command will get 666 permissions (rw for everyone) permissions (the mask bits are in negation - what permissions to take away when creating a file). Technically, a negation of 000 would be 777, but these are just the default permissions - commands will still modify individual bits.

This will work for commands like mkdir x or touch x. Other commands could explicitly set other permissions. For example log files or secrets are often assigned more restrictive permissions by default. You will still need to remove those files with sudo.

The second script user_shell.sh is more complicated but solves the above issues. Every command is run as a user that is the owner of the /app mountpoint so:

  • there is no problem with accessing any of the host files
  • there is no need to use sudo to remove any of the created files
#!/bin/bash
umask 0000
if [[ $# -eq 0 ]]; then
exec "/bin/bash"
else
exec "$@"
fi
#!/bin/bash
set -eu
user=myuser
mountpoint=/app
desired_uid=`stat -c '%u' "$mountpoint"`
existing_uid=`id "$user" -u 2>/dev/null || echo -1`
if [[ $existing_uid -eq -1 ]]; then
echo "Creating user $user with $desired_uid (for access to $mountpoint)"
useradd -m \
--no-log-init \
--uid ${desired_uid} \
--gid 100 \
-s /bin/bash \
${user}
else
if ! [[ $existing_uid -eq $desired_uid ]]; then
echo "User $user already exists with a wrong uid ($existing_uid != $desired_uid)"
exit -1
fi
fi
if [[ $# -eq 0 ]]; then
su "$user"
else
cmd="cd $PWD && "$(printf ' "%s"' "$@")
su "$user" -c "$cmd"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment