TExcelTAD
Home › Docker › EXPOSE and USER

EXPOSE and USER

EXPOSE documents which network ports the application inside the image listens on. USER sets which user the following instructions, and the container's main process, run as. Both are small instructions with big misunderstandings around them.

EXPOSE is documentation

dockerfile
EXPOSE 8000
EXPOSE 53/udp
EXPOSE 9000-9002

EXPOSE does not open or publish anything. It records metadata in the image ("this app listens on 8000/tcp") that tools and humans can read. To make a port reachable from the host you still publish it at run time:

Command Effect
docker run -p 8080:8000 shop host port 8080 → container port 8000 (works with or without EXPOSE)
docker run -P shop publish every exposed port on a free random host port
docker run shop nothing published; other containers on the same network can still connect

The model below parses EXPOSE arguments and shows what -P would do. Real Docker asks the kernel for free ephemeral ports; here they are handed out in order to keep the output stable.

python · try it yourself
def parse_expose(args):
    ports = []
    for item in args.split():
        spec, _, proto = item.partition("/")
        proto = proto or "tcp"
        if "-" in spec:
            low, high = map(int, spec.split("-"))
            ports += [(p, proto) for p in range(low, high + 1)]
        else:
            ports.append((int(spec), proto))
    return ports

exposed = []
for line in ["8000", "53/udp", "9000-9002"]:
    exposed += parse_expose(line)

print("ExposedPorts:", [f"{p}/{proto}" for p, proto in exposed])

next_free = 32768
print("docker run -P:")
for port, proto in exposed:
    print(f"  0.0.0.0:{next_free} -> {port}/{proto}")
    next_free += 1
ExposedPorts: ['8000/tcp', '53/udp', '9000/tcp', '9001/tcp', '9002/tcp']
docker run -P:
  0.0.0.0:32768 -> 8000/tcp
  0.0.0.0:32769 -> 53/udp
  0.0.0.0:32770 -> 9000/tcp
  0.0.0.0:32771 -> 9001/tcp
  0.0.0.0:32772 -> 9002/tcp

Tip: still write EXPOSE for every port your app listens on. docker inspect, docker run -P, Compose and many platforms read it.

USER: stop running as root

By default the process in a container runs as root (UID 0). Container root is limited by namespaces and capabilities, but if an attacker breaks out through a kernel or runtime bug, or you mount a host directory, root inside can mean root outside. Running as an unprivileged user is one of the cheapest security wins.

dockerfile
FROM python:3.12-slim
RUN groupadd --system --gid 10001 app \
 && useradd --system --uid 10001 --gid app --no-create-home app
WORKDIR /app
COPY --chown=app:app . .
USER app
CMD ["python", "server.py"]
  • USER app (or USER 10001:10001) affects all later RUN, CMD and ENTRYPOINT instructions.
  • Put it after steps that need root, such as installing packages.
  • A numeric UID is the most portable choice: platforms such as Kubernetes with runAsNonRoot can only verify a number.
  • Override at run time with docker run --user 10001 ....

Permission problems

Moving to a non-root user often surfaces "Permission denied" errors. They follow the normal Unix rules, which this model checks:

python · try it yourself
files = {
    # path:              (owner uid, group gid, mode)
    "/app/server.py":    (0, 0, 0o644),
    "/app/data":         (0, 0, 0o755),
    "/app/uploads":      (10001, 10001, 0o750),
    "/app/cache":        (0, 10001, 0o770),
}

def can(uid, gid, path, action):
    owner, group, mode = files[path]
    if uid == 0:
        return True                          # root bypasses permission bits
    bit = {"read": 4, "write": 2}[action]
    if uid == owner:
        perms = (mode >> 6) & 7
    elif gid == group:
        perms = (mode >> 3) & 7
    else:
        perms = mode & 7
    return bool(perms & bit)

for uid, gid, who in [(0, 0, "root"), (10001, 10001, "app")]:
    for path, action in [("/app/server.py", "read"), ("/app/data", "write"),
                         ("/app/uploads", "write"), ("/app/cache", "write")]:
        ok = can(uid, gid, path, action)
        print(f"{who:<5} {action:<5} {path:<15} {'ok' if ok else 'Permission denied'}")
root  read  /app/server.py  ok
root  write /app/data       ok
root  write /app/uploads    ok
root  write /app/cache      ok
app   read  /app/server.py  ok
app   write /app/data       Permission denied
app   write /app/uploads    ok
app   write /app/cache      ok

As root everything works, which is why such bugs hide until you add USER. The fixes are to create writable directories with the right owner (COPY --chown, or RUN mkdir /app/data && chown app /app/data before USER), and to write only to a few known places such as /tmp or a mounted volume.

Low ports and non-root users

Traditionally only root could listen on ports below 1024. Docker sets net.ipv4.ip_unprivileged_port_start=0 inside containers, so on current Docker a non-root process can bind port 80 in its own network namespace. Many images still listen on a high port such as 8080 for portability (Kubernetes and Podman do not always apply the same setting), and map it at run time: -p 80:8080.

Test yourself

An image has EXPOSE 3000. You run docker run myapp. Can you open http://localhost:3000 on the host?

  1. Yes, EXPOSE publishes the port
  2. No, the port is not published without -p or -P
  3. Only on Windows
  4. Only if the app runs as root

Where should USER app usually go in a Dockerfile?

  1. Before FROM
  2. Before installing system packages
  3. After the steps that need root, before CMD
  4. It must be the last line after CMD

Why are numeric UIDs (e.g. USER 10001) often preferred over names?

  1. Names are not allowed
  2. Orchestrators can verify a numeric UID is not 0 without reading /etc/passwd
  3. Numbers make images smaller
  4. They run faster