When you run a Docker container and write files to the host system using volume mounts (-v
), you might notice something annoying: the files are owned by root. This happens because, by default, containers run as the root user. This tutorial demonstrates how to run Docker container with specific user.
Let's use alpine/curl
to download an image and save it to the current directory on your host:
docker run -it --rm -v ./:/data alpine/curl -o /data/image.png https://httpbin.org/image/png
Now check the file ownership with ls -l
. Output:
total 8
-rw-r--r-- 1 root root 8090 Jul 14 15:47 image.png
The file was created by root inside the container, so it appears owned by root on your host too.
You can override the user that Docker runs as using the -u
option. For example, if your UID and GID are both 1000
:
docker run -it --rm -v ./:/data -u 1000:1000 alpine/curl -o /data/image.png https://httpbin.org/image/png
Hard-coding UID and GID is fine if you're sure of your IDs, but a safer, more portable way is to use the current user's UID and GID with $(id -u):$(id -g)
:
docker run -it --rm -v ./:/data -u $(id -u):$(id -g) alpine/curl -o /data/image.png https://httpbin.org/image/png
Check the file again with ls -l
. Output:
total 8
-rw-r--r-- 1 john john 8090 Jul 14 15:47 image.png
Now the file is owned by specific user.
Leave a Comment
Cancel reply