In this post, we'll create a user dynamically inside a Docker container with the use UID and GID as the user on the host who ran the container.
Previously, we addressed the issue of accessing a mounted volume inside a container as user root inside the container with Docker Compose here: https://dev.to/frederickollinger/docker-compose-access-a-mounted-volume-inside-a-container-41kf
But this solution wound up creating artifacts which were owned by root which meant that accessing them as a regular user on the host was more difficult.
Thus, we actually want to have a user inside the Docker container which is the same as the host.
The 1st step is to make a bash script which will create a new user inside the container dynamically.
Create a script called entrypoint.sh:
#!/bin/env bash
USER=container
useradd -u $2 $USER -d /home/$USER
chown container /home/$USER
su $USER
This script will basically add a new user called container when the Docker container is 1st run and use the user id passed into the container.
Next create Dockerfile in the same directory:
FROM centos:7
USER root
COPY entrypoint.sh /usr/sbin/entrypoint.sh
RUN chmod a+x /usr/sbin/entrypoint.sh
ENTRYPOINT ["/usr/sbin/entrypoint.sh"]
This Dockerfile will run our entrypoint.sh script when it's first run. It needs to start as root but then it will change to the container user which happens to have the same user id as whomever started the container.
Build the container, in this example as userdemo:
docker build -t userdemo .
Now run the container.
docker \
run \
--rm \
--name=userdemo \
--hostname=userdemo \
--workdir=/home/container \
-v `pwd`/project:/home/developer/project \
userdemo \
/bin/bash `id -u`
In this example, you will have a folder called "project" which is mounted inside the container as /home/container/project. You can change this or even add more lines with the volume mount flag.
Top comments (0)