symfony docker permission problems for cache files

I'd think changing www-datas userid to your host-user's id is a good solution, as permissions for the host user are fairly easy to setup.

#change www-data`s UID inside a Dockerfile
RUN usermod -u [USERID] www-data 

user id 1000 is the default for most linux systems afaik... 501 on mac
you can run id -u on the host system to find out.

You could then log into the container to run symfony commands as www-data

docker exec -it -u www-data [CONTAINER] bash

I was wondering how you could set the userid dynamically on container build. I guess passing it via --build-arg to docker-compose would be the way

docker-compose build --build-arg USERID=$(id -u)

...but haven't managed to access that var in the Dockerfile yet.


Adding to Max's answer

Note that these ideas can be used for non-symfony apps too.

Dockerfile:

# 1000 is default, in case --build-arg is not passed with the build command.
ARG USER_ID=1000
ARG GROUP_ID=1000
ARG HOME_DIR=/home/www-data
# Change user ID & group ID & home directory & shell of www-data user.
# We change home dir because some custom commands may use home dir
# for caching (like composer, npm or yarn) or for another reason.
RUN mkdir ${HOME_DIR} \
    && chown -R ${USER_ID}:${GROUP_ID} ${HOME_DIR} \
    && usermod --uid ${USER_ID} --home ${HOME_DIR} --shell /bin/bash www-data \
    && groupmod --gid ${GROUP_ID} www-data

And if you want to run commands as www-data user in Dockerfile/ENTRYPOINT/CMD etc. you can use su like this:

su - www-data -c "cd /var/www/html && composer install && npm install && node_modules/.bin/encore dev --watch &"

Build command:

# $(id -u) gets the current user's ID and $(id -g) gets the current user's group ID.
# If you want to use another ID go ahead and replace them.
docker-compose build --build-arg USER_ID=$(id -u) --build-arg GROUP_ID=$(id -g)
# or
docker build --build-arg USER_ID=$(id -u) --build-arg GROUP_ID=$(id -g) .