| |

Docker 55 🐳 User Namespaces Mapping (userns-remap): Mapping Container Root to Host Unprivileged User

⏱️ Estimated read: 16 min | |

A container runs as root inside its own namespace by default. Without user namespace remapping, that root is the same root that owns the host. A process that escapes the container, or a kernel vulnerability that lets a process break out of the namespace, lands on the host as root. User namespace remapping (userns-remap) changes this equation. It maps the container’s root (UID 0) to a high-numbered, unprivileged UID on the host. The container still believes it is root. The host sees an anonymous user with no privileges. Even a successful escape yields nothing useful.

Key point: userns-remap is the single most effective mitigation against container escape, because it removes the prize. An attacker who breaks out of a remapped container does not become host root; they become an unprivileged user with a UID that does not even correspond to a real account.


Why userns-remap exists

The root-sharing problem. Every container shares the host kernel. Namespaces isolate what the container can see, but they do not change what the kernel considers the process’s UID. Without remapping, a container process running as root is root to the kernel. A namespace escape, a kernel bug, or a misconfigured mount can expose that root to the host.

The escape payoff problem. Container escapes are rare but they happen. When they do, the attacker’s goal is to reach host root. If the container’s root is mapped to UID 100000 on the host, the escape yields a process that cannot read /etc/shadow, cannot modify system binaries, and cannot access other users’ files. The escape still happens, but the damage is contained.

The defense-in-depth problem. userns-remap is a layer. It does not replace capabilities, seccomp, or AppArmor/SELinux. Those layers restrict what the process can do inside the container. userns-remap restricts what the process can do if it escapes. The layers are independent, and the combination is stronger than any one alone .

The multi-tenant problem. A host running containers for multiple customers cannot afford one tenant’s compromise to affect another. MCS categories in SELinux isolate files, but userns-remap isolates the UID itself. Two containers from different tenants map to different host UID ranges, and neither can access the other’s files even if a mount is misconfigured.

The compliance problem. CIS Docker Benchmark and NIST SP 800-190 recommend enabling userns-remap. Auditors increasingly look for it as a baseline control. It is one of the few settings that changes the security posture from “root inside the container is root” to “root inside the container is nobody” .

The operational cost problem. userns-remap is not free. It changes the ownership of files created by containers, breaks bind mounts that expect root ownership, and requires careful management of subordinate UID ranges. The cost is real, and it is why the setting is not enabled by default.


a. How userns-remap works

The remapping is managed through two files on the host: /etc/subuid and /etc/subgid. Each file assigns a range of subordinate UIDs or GIDs to a user or group. Docker uses these ranges to build the mapping .

The subordinate UID files

An entry in /etc/subuid has three fields: the username, the starting UID of the range, and the count of UIDs in the range.

dockremap:165536:65536

This entry assigns the user dockremap a range of 65,536 UIDs starting at 165,536. Inside the container, UID 0 (root) maps to host UID 165536. UID 1 maps to 165537, and so on up to UID 65535 mapping to 231071 .

The /etc/subgid file works the same way for group IDs.

The default remap user

When "userns-remap": "default" is configured, Docker creates a user and group called dockremap and assigns it a subordinate range. When a specific user is named, that user’s existing range is used .

{
  "userns-remap": "default"
}

The dockremap user owns the namespace storage directory under /var/lib/docker/ and exists primarily as an implementation detail .

The uid_map and gid_map

Inside the container, /proc/self/uid_map shows the mapping. A container process running as UID 0 sees a map that translates UID 0 to a high host UID.

docker run --rm alpine cat /proc/self/uid_map
#          0     165536      65536

The three columns are: the container UID, the host UID, and the count. The container’s UID 0 through 65535 maps to host UIDs 165536 through 231071 .

Verifying the mapping

From the host, the container process appears with the remapped UID.

docker run -d --name test alpine sleep 3600
ps aux | grep sleep
# 165536 ... sleep 3600

The process is running as UID 165536 on the host, not as root. Inside the container, it is root .

The Docker daemon configuration

The setting lives in /etc/docker/daemon.json. After editing, the daemon must be restarted.

{
  "userns-remap": "default"
}
sudo systemctl restart docker

The setting applies to all containers by default. Individual containers can opt out with --userns=host, which shares the host’s user namespace and reverses the remapping for that container .


b. The volume permission problem

The most common practical issue with userns-remap is volume permissions. A bind-mounted host directory owned by UID 1000 (a normal user) appears inside the container as UID 65534 (nobody), because UID 1000 is outside the container’s mapped range. The container cannot read or write the files .

The symptom

mkdir -p /tmp/data && echo hello > /tmp/data/file.txt
docker run --rm -v /tmp/data:/data alpine cat /data/file.txt
# cat: can't open '/data/file.txt': Permission denied

The file is owned by the host user (UID 1000). The container sees it as nobody (65534), which is the kernel’s overflow UID for unmapped UIDs. The container’s root (remapped to 165536) cannot access it .

The reverse problem

Files created by the container are owned by the remapped UID on the host.

mkdir -p /tmp/containerdata && chmod 777 /tmp/containerdata
docker run --rm -v /tmp/containerdata:/data alpine touch /data/from-container.txt
ls -la /tmp/containerdata/from-container.txt
# -rw-r--r-- 1 165536 165536 ... from-container.txt

The file is owned by UID 165536, which does not correspond to a real user .

The ownership fix

The direct fix is to set the host directory’s ownership to the remapped UID range.

REMAP_UID=$(grep dockremap /etc/subuid | cut -d: -f2)
sudo chown -R $REMAP_UID:$REMAP_UID /tmp/data

The container can now read and write the directory, because the host UID matches the container’s root mapping .

The named volume alternative

Named Docker volumes are managed by Docker and are created with the correct ownership automatically. They avoid the permission mismatch because Docker controls the directory on the host.

docker run --rm -v myvolume:/data alpine touch /data/file.txt

The file is created inside the volume with the remapped ownership, and future containers using the same volume see consistent permissions.

The chown in Dockerfile pattern

When a container needs to write to a specific path inside its own filesystem, the Dockerfile can set ownership to the remapped UID. However, this must be done knowing the remap range, which is host-specific.

RUN mkdir /appdata && chown 165536:165536 /appdata

The hardcoded UID ties the image to a specific host configuration. A more portable approach is to run the container as a non-root user inside the namespace, so the UID mapping is consistent.


c. Limitations and operational considerations

userns-remap changes the ownership model of the host’s Docker data. This has consequences beyond volume mounts.

The image and container layer ownership

When remapping is enabled, Docker adjusts the ownership of image layers and container layers to the remapped UID range. Existing images and containers created before remapping may not work correctly. The Docker documentation recommends enabling userns-remap on a fresh Docker installation rather than an existing one .

The data directory structure changes from /var/lib/docker/ to /var/lib/docker/<remapped-uid>.<remapped-gid>/. The original data remains untouched, and Docker uses the new directory for remapped containers .

The contained image store conflict

Some Docker configurations use the containerd image store for multi-architecture images and provenance. Enabling userns-remap may disable this store and revert to the older image storage backend. The trade-off is between the security of remapping and the features of the newer store .

The CVE-2021-21284 precedent

A vulnerability in Docker Engine’s userns-remap feature, tracked as CVE-2021-21284, allowed a process with remapped-root access to write files that the Docker daemon would later interpret with real host-root privileges. The flaw was in how the daemon set ownership of sensitive data-root directories. It was patched in Docker Engine 19.03.15 and 20.10.3. The lesson is that userns-remap is a security control, and like any control, it can have bugs. Keeping Docker updated is part of the hardening .

The single-UID mapping edge case

Some configurations use a single-UID mapping rather than the full 65,536 range. In this case, only one UID is mapped, and all other UIDs appear as the overflow UID (65534). This can break applications that expect to traverse directory trees where ancestors are owned by root, because root does not exist in the container’s namespace .

The application compatibility requirement

Some applications assume they are running as root and attempt operations that fail when the host UID is unprivileged. A process that tries to chown a file to another user may fail because the mapped range does not include that user. The application must be designed to work within the mapped range.


Complete Example Session

# ============================================
# PART 1: ENABLE USERNS-REMAP
# ============================================

# Edit the daemon configuration
sudo tee /etc/docker/daemon.json <<'EOF'
{
  "userns-remap": "default"
}
EOF

# Restart Docker
sudo systemctl restart docker

# ============================================
# PART 2: VERIFY THE MAPPING
# ============================================

# Check the subordinate UID range
cat /etc/subuid
# dockremap:165536:65536

cat /etc/subgid
# dockremap:165536:65536

# Check inside a container
docker run --rm alpine cat /proc/self/uid_map
#          0     165536      65536

# ============================================
# PART 3: VERIFY ON THE HOST
# ============================================

docker run -d --name test alpine sleep 3600
ps aux | grep sleep
# 165536 ... sleep 3600

docker rm -f test

# ============================================
# PART 4: THE VOLUME PERMISSION PROBLEM
# ============================================

mkdir -p /tmp/data
echo "hello" > /tmp/data/file.txt
chmod 600 /tmp/data/file.txt

docker run --rm -v /tmp/data:/data alpine cat /data/file.txt
# cat: can't open '/data/file.txt': Permission denied

# The host file is owned by the host user.
# The container sees it as nobody (65534).

# ============================================
# PART 5: THE OWNERSHIP FIX
# ============================================

REMAP_UID=$(grep dockremap /etc/subuid | cut -d: -f2)
REMAP_GID=$(grep dockremap /etc/subgid | cut -d: -f2)

sudo chown -R $REMAP_UID:$REMAP_GID /tmp/data

docker run --rm -v /tmp/data:/data alpine cat /data/file.txt
# hello

# ============================================
# PART 6: FILES CREATED BY THE CONTAINER
# ============================================

mkdir -p /tmp/containerdata
chmod 777 /tmp/containerdata

docker run --rm -v /tmp/containerdata:/data alpine touch /data/file.txt

ls -la /tmp/containerdata/file.txt
# -rw-r--r-- 1 165536 165536 ... file.txt

# ============================================
# PART 7: NAMED VOLUMES AVOID THE PROBLEM
# ============================================

docker volume create appdata
docker run --rm -v appdata:/data alpine touch /data/file.txt
docker run --rm -v appdata:/data alpine ls -la /data
# -rw-r--r-- 1 0 0 ... file.txt (inside the container)
# On the host, it is owned by the remapped UID.

# ============================================
# PART 8: OPTING OUT FOR A SPECIFIC CONTAINER
# ============================================

docker run --rm --userns=host alpine id
# uid=0(root) gid=0(root) -- real host root

# Use only when the container genuinely needs host namespace access.

# ============================================
# PART 9: THE COMBINED HARDENED BASELINE
# ============================================

# daemon.json
{
  "userns-remap": "default"
}

docker run --rm \
  --cap-drop=ALL \
  --cap-add=NET_BIND_SERVICE \
  --security-opt=no-new-privileges \
  --security-opt seccomp=./profile.json \
  --security-opt apparmor=myapp \
  --read-only \
  --tmpfs /tmp \
  myapp:latest

# userns-remap is a daemon-level setting.
# The other flags are per-container.
# Together they form the layered defense.

# ============================================
# PART 10: TROUBLESHOOTING
# ============================================

# If a container fails to start with userns-remap:
docker run --rm myapp:latest
# Error: failed to create task: OCI runtime create failed

# Check for files with high UIDs in the image:
docker run --rm --entrypoint sh myapp:latest
find / \( -uid 1000000 \) -ls 2>/dev/null

# If found, chown them in the Dockerfile:
# RUN chown -R root:root /path

# Check the daemon logs:
sudo journalctl -u docker | tail -50

The ten parts progressed from enabling userns-remap through verification, the volume permission problem, ownership fixes, named volumes, opting out, the combined baseline, and troubleshooting. The same container examples ran through every part, showing how remapping changes the ownership model.


Quick Reference

Configuration

SettingValue
daemon.json key"userns-remap": "default"
Specific user"userns-remap": "myuser"
Subuid file/etc/subuid
Subgid file/etc/subgid
Default remap userdockremap
Data directory/var/lib/docker/<uid>.<gid>/

Subordinate Range Format

FieldExampleMeaning
UserdockremapThe user owning the range
Start UID165536First UID in the range
Count65536Number of UIDs

Verification Commands

CommandPurpose
cat /etc/subuidShow subordinate UID ranges
docker run --rm alpine cat /proc/self/uid_mapShow the container’s mapping
ps aux | grep sleepShow the host UID of a container process
docker info --format '{{.SecurityOptions}}'Show active security options

Volume Permission Fixes

ApproachCommand
Chown to remapped UIDchown -R 165536:165536 /path
Named volumedocker volume create appdata
Opt out for one container--userns=host

Limitations

LimitationImpact
Bind mount permissionsHost files inaccessible to container
File ownership on hostFiles owned by high UID
Image storeMay disable containerd store
Existing imagesMay need recreation
Single-UID mappingRoot unavailable in namespace

Best Practices

✅ Do This:

// Enable userns-remap in daemon.json.
{ "userns-remap": "default" }  // ✅
# Verify the mapping after enabling.
docker run --rm alpine cat /proc/self/uid_map  // ✅

# Use named volumes instead of bind mounts.
docker volume create appdata  // ✅

# Chown bind mount directories to the remapped UID.
sudo chown -R 165536:165536 /data  // ✅

# Enable on a fresh Docker installation.
# Existing images may need recreation.  // ✅

# Combine with capabilities, seccomp, and AppArmor/SELinux.
--cap-drop=ALL --security-opt seccomp=profile.json  // ✅

# Keep Docker updated to avoid known remap vulnerabilities.
sudo apt upgrade docker-ce  // ✅

❌ Don’t Do This:

# Don't enable userns-remap without testing volumes.
# Bind mounts will break.  // ❌

# Don't use --userns=host without a specific reason.
# It reverses the security control for that container.  // ❌

# Don't hardcode the remapped UID in the Dockerfile.
# It ties the image to one host configuration.  // ❌

# Don't assume existing containers will work.
# The ownership model changes.  // ❌

# Don't skip the verify step.
# A misconfigured remap may silently fail.  // ❌

# Don't forget that the daemon itself still runs as root.
# userns-remap protects containers, not the daemon.  // ❌

Common Pitfalls

PitfallWhy It HappensFix
Volume permission deniedHost file owned by unmapped UIDChown to remapped UID or use named volume
Container fails to startImage contains high UIDsChown files in Dockerfile
Existing containers brokenOwnership model changedRecreate containers
nobody owns filesOverflow UID for unmapped UIDsExpected behavior; adjust ownership
Image store disableduserns-remap conflictAccept the trade-off
Daemon logs errorsSubuid ranges overlapEnsure ranges are unique
Application cannot chownMapped range lacks the target UIDRedesign the application
CVE-2021-21284Unpatched DockerUpgrade to 19.03.15+ or 20.10.3+

Real-World Examples

1. Enable userns-remap

{ "userns-remap": "default" }

2. Verify the Mapping

docker run --rm alpine cat /proc/self/uid_map

3. Check Host Process UID

ps aux | grep sleep
# 165536 ... sleep 3600

4. Chown for Bind Mount

sudo chown -R 165536:165536 /data

5. Named Volume

docker volume create appdata
docker run -v appdata:/data alpine touch /data/file

6. Opt Out

docker run --userns=host alpine id

7. Find High UIDs in Image

docker run --entrypoint sh myapp -c 'find / -uid +100000 -ls 2>/dev/null'

8. Fix High UIDs

RUN chown -R root:root /path

9. Check Security Options

docker info --format '{{.SecurityOptions}}'

10. Combined Baseline

docker run --cap-drop=ALL --security-opt seccomp=profile.json myapp

Visual

The Remapping Concept

┌────────────────────────────────────────────────────────────┐
│  WITHOUT USERNS-REMAP                                      │
│                                                            │
│  CONTAINER                    HOST                         │
│  ┌──────────────────┐        ┌──────────────────┐         │
│  │  UID 0 (root)    │───────▶│  UID 0 (root)    │         │
│  │  Full privileges │        │  Full privileges │         │
│  └──────────────────┘        └──────────────────┘         │
│                                                            │
│  A container escape yields host root.                      │
│                                                            │
│  ──────────────────────────────────────────────────────    │
│                                                            │
│  WITH USERNS-REMAP                                         │
│                                                            │
│  CONTAINER                    HOST                         │
│  ┌──────────────────┐        ┌──────────────────┐         │
│  │  UID 0 (root)    │───────▶│  UID 165536      │         │
│  │  Full privileges │        │  No privileges   │         │
│  │  inside namespace│        │  No real account │         │
│  └──────────────────┘        └──────────────────┘         │
│                                                            │
│  A container escape yields an unprivileged user.           │
│                                                            │
└────────────────────────────────────────────────────────────┘

The UID Range

┌────────────────────────────────────────────────────────────┐
│  SUBORDINATE UID RANGE                                     │
│                                                            │
│  /etc/subuid: dockremap:165536:65536                       │
│                                                            │
│  Container UID 0    →  Host UID 165536                     │
│  Container UID 1    →  Host UID 165537                     │
│  Container UID 2    →  Host UID 165538                     │
│  ...                                                       │
│  Container UID 65535 →  Host UID 231071                    │
│                                                            │
│  ┌──────────────────────────────────────────────────┐     │
│  │  CONTAINER NAMESPACE                              │     │
│  │  0 ────────────────────────────────────── 65535   │     │
│  └──────────────────────────────────────────────────┘     │
│                        │                                   │
│                        │  Offset by 165536                 │
│                        v                                   │
│  ┌──────────────────────────────────────────────────┐     │
│  │  HOST                                             │     │
│  │  165536 ───────────────────────────────── 231071 │     │
│  └──────────────────────────────────────────────────┘     │
│                                                            │
│  The host UIDs do not correspond to real users.            │
│  The process has no privileges on the host.                │
│                                                            │
└────────────────────────────────────────────────────────────┘

The Volume Permission Problem

┌────────────────────────────────────────────────────────────┐
│  VOLUME PERMISSION WITH USERNS-REMAP                       │
│                                                            │
│  HOST FILE: /tmp/data/file.txt                             │
│  ┌──────────────────────────────────────────────────┐     │
│  │  Owner: UID 1000 (your user)                      │     │
│  │  Mode:  600                                       │     │
│  └──────────────────────────────────────────────────┘     │
│                        │                                   │
│                        │  Bind mount to /data              │
│                        v                                   │
│  CONTAINER SEES:                                           │
│  ┌──────────────────────────────────────────────────┐     │
│  │  Owner: UID 65534 (nobody, overflow)              │     │
│  │  Mode:  600                                       │     │
│  │                                                   │     │
│  │  Container process runs as UID 0 (→ 165536 host)  │     │
│  │  UID 165536 ≠ UID 65534                           │     │
│  │  Permission denied.                               │     │
│  └──────────────────────────────────────────────────┘     │
│                                                            │
│  FIX: chown -R 165536:165536 /tmp/data                     │
│  Then the container's root owns the directory.             │
│                                                            │
└────────────────────────────────────────────────────────────┘

The Defense Layers

┌────────────────────────────────────────────────────────────┐
│  USERNS-REMAP IN THE LAYERED MODEL                         │
│                                                            │
│  ┌──────────────────────────────────────────────────┐     │
│  │  CAPABILITIES                                     │     │
│  │    May the operation run?                         │     │
│  └──────────────────────────────────────────────────┘     │
│                        │                                   │
│                        v                                   │
│  ┌──────────────────────────────────────────────────┐     │
│  │  SECCOMP                                          │     │
│  │    May the syscall run?                           │     │
│  └──────────────────────────────────────────────────┘     │
│                        │                                   │
│                        v                                   │
│  ┌──────────────────────────────────────────────────┐     │
│  │  APPARMOR / SELINUX                               │     │
│  │    May the resource be touched?                   │     │
│  └──────────────────────────────────────────────────┘     │
│                        │                                   │
│                        v                                   │
│  ┌──────────────────────────────────────────────────┐     │
│  │  USERNS-REMAP                                     │     │
│  │    What UID does the escape yield?                 │     │
│  │    ← This chapter                                  │     │
│  └──────────────────────────────────────────────────┘     │
│                                                            │
│  The first three layers restrict what happens inside.      │
│  userns-remap restricts what happens if those fail.        │
│                                                            │
└────────────────────────────────────────────────────────────┘

Summary

ItemValue
userns-remapMaps container root to an unprivileged host UID
daemon.json"userns-remap": "default"
Subuid file/etc/subuid assigns UID ranges
Subgid file/etc/subgid assigns GID ranges
Default userdockremap
Host UID range165536–231071 (typical)
Volume impactHost files appear as nobody
Fixchown to the remapped UID or use named volumes
Opt out--userns=host
Known CVECVE-2021-21284, patched in 19.03.15+

Key takeaways:

  • userns-remap removes the prize from a container escape. Without it, a container’s root is the host’s root. With it, the container’s root maps to an unprivileged host UID that does not correspond to a real user. An escape yields nothing useful.
  • The mapping is defined in /etc/subuid and /etc/subgid. Each entry assigns a range of subordinate UIDs or GIDs to a user. Docker uses these ranges to build the namespace mapping.
  • The setting is daemon-wide. "userns-remap": "default" in /etc/docker/daemon.json applies to all containers. Individual containers can opt out with --userns=host.
  • Volume permissions change. A bind-mounted host directory owned by a normal user appears inside the container as nobody. The fix is to chown the directory to the remapped UID or to use named volumes.
  • Files created by containers have high UIDs on the host. This is expected. The ownership reflects the remapped range, not a real user.
  • Enable on a fresh installation. userns-remap changes the ownership of image and container layers. Existing images may need recreation.
  • The containerd image store may conflict. Some Docker configurations lose multi-architecture support when userns-remap is enabled. The trade-off is between the newer store and the security control.
  • Keep Docker updated. CVE-2021-21284 was a flaw in the userns-remap implementation itself. It was patched in Docker Engine 19.03.15 and 20.10.3.
  • userns-remap is one layer. It restricts what an escape yields. Capabilities, seccomp, and AppArmor/SELinux restrict what happens before an escape. All layers together form the defense.

Remember: User namespace remapping is the security control that changes what a container escape is worth. Without it, a container’s root is the host’s root, and an escape is a full compromise. With it, the container’s root maps to an unprivileged high-numbered UID on the host, and an escape yields a process with no privileges. The setting lives in the Docker daemon configuration, the mapping is defined in /etc/subuid and /etc/subgid, and the effect is that files created by containers are owned by anonymous UIDs on the host. The cost is volume permission complexity: bind mounts that expect root ownership break, and the fix is to chown the directories to the remapped UID or to use named volumes. The benefit is that a container escape, a kernel vulnerability, or a misconfigured mount no longer yields host root. The container runs the same workload with the same performance, but the blast radius is fundamentally smaller.


Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!