brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: docker exec -u and -w run a command as another user in another folder

Docker
~/tips/tip-docker-exec-workdir-user

docker exec -it -u 1000:1000 -w /config mycontainer ls -l

Runs a command inside a running container as a chosen user and from a chosen folder.

A shell inside a container often starts as root in /, which is rarely where the problem is. Two small flags on docker exec let you land in the right folder as the right user.

-u (or --user) takes <name|uid>[:<group|gid>]. -w (or --workdir) sets the working directory, and without it the command runs in the directory the container was created with. The reference example is docker exec -it -w /root mycontainer pwd, which prints /root.

docker exec -it -u 1000:1000 -w /config mycontainer ls -l

I find the user flag most useful when files in a mounted folder have the wrong owner. Running the command as the same UID and GID the app uses shows you what the app can really read and write, which root would hide. A quick test is to create a file as that user:

docker exec -u 1000:1000 -w /config mycontainer touch testfile

If that fails with a permission error, you have found your problem, and the fix is on the host side, for example with chown.

The UID does not have to exist in the container. One that is not in /etc/passwd still works, but the shell prompt shows an ID instead of a name and tools that look the user up may complain. Remember to delete the test file afterwards. And -w needs a reasonably recent Docker API (1.35 or newer according to the reference), which any current install has.

Further reading: docker container exec

More Docker tips ONBUILD RUN /usr/local/bin/python-build --dir /app/src SHELL ["/bin/bash", "-c"] docker commit <container> myname/testimage:version3 docker import /path/to/exampleimage.tgz docker compose events All Docker tips (192) All topics

Link