如何禁止学生用--userns=host绕过Docker用户命名空间映射以保障主机安全
--userns=host in Docker Great question! As someone who’s set up Docker environments for educational use before, I’ve dealt with exactly this scenario. You’re already on the right track with enabling user namespace (userns) remapping—here’s how to lock down the --userns=host override to keep your host safe while letting students work freely in containers:
1. Enforce Userns Remapping at the Docker Daemon Level
This is the strongest, most reliable safeguard. By setting userns remapping globally in the daemon config, you make it impossible for any user to override it with command-line flags.
- Edit (or create) the Docker daemon config file at
/etc/docker/daemon.json:
The{ "userns-remap": "default" }defaultvalue tells Docker to create a dedicated unprivileged user/group (likedockremap) on the host, which container root will be mapped to. You can also specify a custom existing user if you prefer. - Restart the Docker daemon to apply changes:
sudo systemctl restart docker - Now, any attempt to run
docker run --userns=host ...will fail with an error like:Error response from daemon: User namespaces are enabled in the daemon, so cannot use --userns=host.
2. Use Docker’s Policy JSON for Granular Blocking
If you need more control (e.g., allow trusted staff to use --userns=host but block students), use Docker’s authorization policy to explicitly deny the flag.
- Create or edit
/etc/docker/policy.jsonwith these rules:{ "defaultAction": "allow", "rules": [ { "action": "deny", "condition": { "equals": { "container.usernsMode": "host" } } } ] } - Restart the Docker daemon to activate the policy:
sudo systemctl restart docker - This will block any container creation request that uses
usernsMode=host, even if the daemon’s global userns setting isn’t enabled.
3. Restrict Sudo Access (Supplementary Layer)
If your students use sudo to run Docker commands, you can add an extra layer of protection by limiting their allowed commands in the sudoers file.
- Edit the sudoers file safely with
visudo:sudo visudo - Add a line for your student group (replace
studentswith your actual group name):%students ALL=(ALL) NOPASSWD: /usr/bin/docker run !--userns=host, /usr/bin/docker start, /usr/bin/docker stop, /usr/bin/docker rm - This restricts students to running
docker runwithout the--userns=hostflag, plus basic container management commands. Note: This is a supplementary measure—daemon-level enforcement is still your primary defense, as clever students might find workarounds for sudo restrictions.
Verify Your Setup
Have a student test the blocked command to confirm it works:
docker run --userns=host alpine echo "Test"
They should receive an error indicating the command is blocked.
内容的提问来源于stack exchange,提问作者Big Papoo

