Run a Command as Root in a Running Docker Container
Run a command as root in a running container with docker exec -u 0. By default exec uses the container's own user, which is not root after --user or USER.
A command inside a container fails with "Permission denied", and the same container ran as root before you added --user.
docker run -d --name app --user 1000:1000 alpine:3.20 sleep 60 > /dev/null
docker exec app id -u
docker exec app touch /etc/marker; echo "status: $?"
docker exec -u 0 app id -u
docker exec -u 0 app touch /etc/marker; echo "status: $?"
docker rm -f app > /dev/null1000
touch: /etc/marker: Permission denied
status: 1
0
status: 0docker exec starts the new process with the user the container was created with, which is the USER of the image or the --user option of docker run. It is not root unless the image says so. -u 0, or -u root, overrides that for one command and leaves the container's main process alone, as the docker exec reference describes. The first touch fails on /etc, and the second works.
Root in a container is root on the host as far as the kernel is concerned unless user namespaces are on, so use -u 0 for debugging and not as a routine way to fix permissions. A change made that way is lost when the container is recreated, so fix the image or the volume ownership instead.