Back to all posts
·7 min read

Hardening Docker containers: non-root users, read-only file systems and least privilege

For many teams, putting an application into a container ends at "it works, done." The image builds, the service starts, the health check is green. But inside that container the process is most likely running as root, can write anywhere on the file system and holds a set of kernel privileges it never needs. When a vulnerability is found in the application, what the attacker gets is exactly the sum of those defaults.

The goal of container hardening is not to prevent vulnerabilities but to limit the damage when one is found. In this post I use an ASP.NET Core service as the example and walk through steps you can apply without making daily work harder: a non-root user, a read-only file system, dropped capabilities, smaller images, resource limits and automated checks that keep these rules in place.

The real risk of running as root

Root inside a container is not the same as root on the host; namespaces and default security profiles put a wall in between. Still, that wall is thin. A process running as root in a container can modify every file in the image, install packages, write without restriction to mounted volumes, and has a much better chance of reaching the host when it meets a kernel vulnerability or a misconfigured mount.

In practice, the question to ask is: "If this application had a remote code execution vulnerability, what could an attacker do?" In an image that runs as root, has a writable file system and is full of tools, the answer is "almost anything." Each of the steps below narrows that answer a little further.

Defining a non-root user in the image

The first and most effective step is to run the process as an unprivileged user. The official .NET 8 and later images ship with a ready-made app user whose ID is exposed through the APP_UID environment variable. This is also why the application listens on port 8080 by default: ports below 1024 require an extra privilege.

FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY . .
RUN dotnet publish Shop.Api/Shop.Api.csproj -c Release -o /app/publish

FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /app
COPY --from=build /app/publish .
USER $APP_UID
EXPOSE 8080
ENTRYPOINT ["dotnet", "Shop.Api.dll"]

There is an important detail here: the application files are copied as owned by root, and the app user can only read them. That is a deliberate choice; the application should not be able to modify its own binaries. If there is a directory it really needs to write to, give only that directory to the user with COPY --chown or RUN mkdir ... && chown.

If you use a base image without a ready-made user, create one yourself and use a numeric ID in the USER line. Kubernetes' runAsNonRoot check cannot verify whether a user name maps to root; it wants to see a numeric UID.

RUN groupadd --system --gid 10001 app \
 && useradd --system --uid 10001 --gid app --no-create-home app
USER 10001

To verify the change, looking at the output of docker run --rm <image> id is enough. If you see uid=0, the job is not done.

A read-only root file system

The next step is to make the container's root file system read-only. That way an attacker cannot download tools into the image, cannot change configuration files and cannot leave a persistent modification behind. The places an application genuinely needs to write to are usually few: /tmp for temporary files and perhaps a cache directory. For these, use in-memory tmpfs mounts.

services:
  api:
    image: registry.example.com/shop-api:1.4.2
    read_only: true
    tmpfs:
      - /tmp:size=64m

When you turn this on, you will see the application trying to write to unexpected places, and that is a useful discovery in itself. In ASP.NET Core, the typical example is the Data Protection keys. Their default location is the user's home directory, which is not writable on a read-only system. These keys should not disappear with the container anyway; pointing them to a persistent volume or a shared store solves this problem and also prevents broken sessions when you run more than one replica. Writing logs to standard output instead of files is part of the same approach.

Dropping Linux capabilities and disabling privilege escalation

Linux splits root privileges into small pieces called "capabilities": changing network settings, changing file ownership, binding to low ports and so on. By default, Docker gives a container a subset of these capabilities. A typical web API needs none of them.

services:
  api:
    cap_drop:
      - ALL
    security_opt:
      - no-new-privileges:true

cap_drop: [ALL] removes every capability. If you really need one, add only that one back with cap_add and write down why next to it. no-new-privileges prevents the process from gaining more privileges at runtime through paths such as setuid binaries. Together with a non-root user, these two settings significantly narrow the impact of a vulnerability.

If you use Kubernetes, the same intent is expressed in the pod's securityContext:

securityContext:
  runAsNonRoot: true
  runAsUser: 1654
  allowPrivilegeEscalation: false
  readOnlyRootFilesystem: true
  capabilities:
    drop: ["ALL"]

Less content, smaller attack surface

Every tool in the image is a tool the attacker can use. A shell, a package manager, curl or a compiler are not needed for a web service to run. This is where the real value of multi-stage builds shows up: the SDK and build tools stay in the first stage, and only the runtime and the published files go into the final image.

If you want to go a step further, you can consider minimal base images that contain no shell and no package manager. Microsoft's "chiseled" images for .NET and the "distroless" approach for other ecosystems serve this purpose. There is a cost: you cannot exec into the container and debug from a shell. That is why observation from the outside, such as health checks, structured logs and metrics, needs to be in place beforehand. My preference is to keep the production image minimal and to cover debugging needs with a separate tooling container.

A side benefit of a small image is security scanning. The fewer packages there are in the image, the fewer vulnerabilities the scanner reports, and the findings that really matter do not get lost in the noise.

Resource limits and dangerous shortcuts

Hardening is not only about privileges; a container should also be unable to lock up the whole host. Setting limits for memory and process count confines the damage of a memory leak or runaway process creation to a single container.

services:
  api:
    mem_limit: 512m
    pids_limit: 200

Beyond that, you need to stay away from a few shortcuts that undo all the gains of hardening in a single line:

  • privileged: true: Gives the container almost host-level privileges. There is no justification for it in a normal application service.
  • Mounting the Docker socket (/var/run/docker.sock): Giving a container the right to manage Docker practically means giving it root on the host.
  • Mounting host directories as writable: If it is necessary, mount the narrowest possible directory, read-only with :ro where you can.
  • Using the host network (network_mode: host): Removes network isolation and exposes everything the service listens on directly.

Checking the rules automatically

The value of these settings depends on them staying in place. One day a hastily added USER root line, or a privileged flag turned on for debugging and then forgotten, wastes all the effort. That is why the rules need to move into the CI pipeline instead of relying on attention during code review.

A practical start consists of three checks. First, lint Dockerfiles and require a USER line in the final stage. Second, run the built image through a security scanner and stop the pipeline on findings above a certain severity. Third, if you use Kubernetes, define a policy in the cluster that rejects pods running as root or allowing privilege escalation. All of these checks should have an exception mechanism, but the reason for each exception should be written down and visible.

Closing

Container hardening does not have to be a large one-off project. A non-root user and dropped capabilities are a change of a few lines for most services and bring the biggest gain. A read-only file system helps you learn where your application writes. Minimal images and automated checks preserve these gains over time. At every step, ask yourself the same question: "If this service were compromised, what would the attacker be left with?" The shorter the answer, the better you have done your job.