Skip to content
shellhacks.dev
DevOps

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.

1 min read
Summarize in AI

A command inside a container fails with "Permission denied", and the same container ran as root before you added --user.

Shell
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/null
Text
1000
touch: /etc/marker: Permission denied
status: 1
0
status: 0

docker 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.

Share

More snippets

DevOps

Run a Script as a Pre-Merge Check in CI

Run a check script as a pre-merge gate and let its exit status decide. Without set -e, a script ends with the status of its last command and hides earlier failures.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.