Docker-compose: Create files with same user:group

Dr. Adam Nielsen
2 min readDec 9, 2021

--

If you create files in your docker container, they will have for Linux the user root:root . This means, you don’t have access to the files outside of the container (except with sudo). To avoid this, you can create a user in your docker-compose file like this:

version: '3'
services:
app:
image: alpine
user: "${UID:-1000}:${GID:-1000}"

This will create user with id:group 1000:1000 which is for most Linux systems your default setting. You can check your uid and gid by entering id in your shell. If your user has a different id and group you can just change the default value.

You are now able to access the files created in your docker image from outside the container. Congratulations!

You made it!!

Remarks

What if I need dynamic UID/GID?

Maybe you share your software with other developers or you working on multiple machines where users have not all the same uid:gid. In this case, you may either specify this in your .env file or set the variable before you start your container:

export UID=${UID}
export GID=${GID}
docker-compose up -d

You can also check https://blog.giovannidemizio.eu/2021/05/24/how-to-set-user-and-group-in-docker-compose/ for other alternatives how to pass the variables.

My user has no name and host?

Although your user id and group id are now identical between your container and your PC/Laptop, the user does not exists on your docker image itself. Meaning you don’t have a name, a home and so on when you bash into your container. If you want to avoid this, you have to create in your Dockerfile your user like this:

FROM IMAGEARG WWWGROUP
ARG WWWUSER
ARG USERNAME
// RUN ...
// COPY ...
// ETC..
RUN groupadd -g $WWWGROUP -o $USERNAME
RUN useradd -m -u $WWWUSER -g $WWWGROUP -o -s /bin/bash $USERNAME
USER $USERNAME

These variables have to be passed by your docker-compose.yml file.

version: '3'
services:
app:
build:
context: ./
dockerfile: Dockerfile
args:
WWWGROUP: '${WWWGROUP:-1000}'
WWWUSER: '${WWWUSER:-1000}'
USERNAME: '${USERNAME:-HermineGranger}'
image: beauty-bill
volumes:
- ./:/var/www/html

Here I used again default values that can be overwritten by your .env file (or the other possibilities, see What if I need dynamic UID/GID?

Since you made changes do your Dockerfile make sure to rebuild your image on first run:

docker-compose up -d --build

Now the user exists on your image with same uid and gid as your machine user. Enjoy! :)

References:

--

--

Dr. Adam Nielsen
Dr. Adam Nielsen

Written by Dr. Adam Nielsen

PHD in math. and Laravel / Vue Full-Stack-Developer

No responses yet