Don't Give Your Docker Container Host Privileges
You should not give your Docker containers host privileges. Learn why and better alternatives including adding specific Docker capabilities and devices.
Table of Contents 📖
The Docker --privileged Flag
Docker has a --privileged flag that grants a container elevated permissions, allowing it to access and perform operations typically reserved for the host system. This basically means that if you are root in a container you have root privileges on the host system. Therefore, this flag comes with significant security implications and should be used carefully. For example, the command below grants the container full access to critical host resources.
docker run --rm -it --privileged --name privileged-container -v /sys:/sys:ro -v /dev:/dev ubuntu:latest bash
INFO: Typically, the --privileged flag should only be used when running Docker-in-Docker (DinD). For example, containers that need to run Docker commands themselves that build and manage containers often use this flag to access the Docker daemon and host filesystem.
What to Do Instead
It is best practice to avoid the --privileged flag when possible. Instead of granting all privileges, you should add specific capabilities with the --cap-add flag and --device flag. For example, the following command grants access to a specific device and grants the SYS_ADMIN capability (allowing certain administrative operations like mounting filesystems).
docker run --rm --name custom-container --device=/dev/sda:/dev/sda --cap-add=SYS_ADMIN -v /sys:/sys:ro ubuntu:latest echo "Hello World"
This method reduces the security risks by granting only the permissions and resources needed for the container's operation.
WARNING: If the privileged flag is unavoidable for you, consider running the privileged container on a separate physical or virtual machine to isolate the risk.