Docker › Image

Hardening Docker images with non-root users and Trivy scans

Avoid container root risks by isolating processes with fixed non-root UIDs, preventing OverlayFS bloat with COPY --chown, and gating CI with Trivy.

Hardening Docker images with non-root users and Trivy scans

Inside a container, root is still UID 0 on the host Linux kernel. This post covers why default root containers are risky, how to switch to a fixed-UID non-root user without doubling your image size, and how to block vulnerable images in CI with Trivy.


Why container isolation alone is not enough

A common misconception is that containers behave like virtual machines with a separate kernel and hypervisor boundary. They don’t. A container is a set of regular processes sharing the host Linux kernel, separated only by namespaces and cgroups.

Container root is host UID 0

If your Dockerfile omits a USER instruction, the container runs as root (UID 0) by default:

1
2
3
4
5
# Inside the container
$ whoami
root
$ id
uid=0(root) gid=0(root) groups=0(root)

Check that same process from the host terminal with ps, and you’ll see the host kernel running it under host UID 0 (root):

1
2
3
# On the host OS
$ ps -eo pid,user,args | grep java
19420 root    java -jar app.jar

Linux namespaces isolate PIDs, mounts, and network interfaces, but unless you explicitly enable user namespace remapping, UID 0 inside the container maps straight to UID 0 on the host kernel.

flowchart TD
    subgraph ContainerA["Risky: Root Container"]
        CA_P["App Process (UID 0)"]
    end
    subgraph ContainerB["Safer: Non-root Container"]
        CB_P["App Process (UID 1001)"]
    end
    subgraph Host["Host Linux Kernel"]
        HK["Syscall and permission checks"]
    end
    CA_P -->|"UID 0 syscalls (breakout risk)"| HK
    CB_P -->|"Unprivileged (host access blocked)"| HK
    style ContainerA fill:#ffebee,stroke:#c62828,stroke-width:2px
    style ContainerB fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px

What happens during a container breakout

Suppose an attacker exploits a remote code execution (RCE) bug in your web app and gets a shell:

  • As a non-root user: They can’t install packages with apt or apk, can’t write to host-mounted root paths, and have to chain a privilege escalation exploit just to gain root inside the container. The blast radius stays contained.
  • As root: They already hold UID 0. If the container exposes /var/run/docker.sock, mounts sensitive host paths, keeps extra Linux capabilities, or runs on a host with a kernel or runC bug (like CVE-2019-5736), escaping to full host control becomes dramatically easier.

Running as a non-root user is your first defense-in-depth layer: even if an application gets compromised, it keeps the attacker from immediately owning the host.


Creating fixed-UID non-root users in Dockerfiles

To drop root privileges, create a dedicated system group and user for your base distribution and switch to it with USER.

Syntax by base distribution

Debian / Ubuntu (glibc)

Use groupadd and useradd with a disabled login shell:

1
2
3
# Create system group and user with fixed UID/GID and no login shell
RUN groupadd -r -g 1001 appgroup && \
    useradd -r -u 1001 -g appgroup -s /usr/sbin/nologin -d /app appuser

Alpine Linux (musl libc)

Alpine uses BusyBox’s addgroup and adduser:

1
2
3
# Create system group and user on Alpine
RUN addgroup -g 1001 -S appgroup && \
    adduser -u 1001 -S -G appgroup -s /sbin/nologin appuser

Why you should pin numeric UIDs and GIDs

Letting the OS auto-assign a UID can produce 100, 101, or 1000 depending on the base image version. Pinning explicit IDs like 1001 avoids two operational headaches:

  1. Kubernetes Pod Security Standards: Policies with runAsNonRoot: true and runAsUser: 1001 expect a numeric UID—Kubernetes refuses to verify USER appuser by name alone unless the numeric UID is known.
  2. Host volume permissions: Matching numeric UIDs prevents Permission denied errors when mounting host or persistent volumes.

Avoiding OverlayFS bloat and write-permission errors

Teams adopting non-root containers usually hit two snags right away: doubled image size and runtime write failures on log or temp directories.

Anti-pattern: RUN chown -R doubles your image size

A natural first attempt is copying the JAR and then fixing ownership with chown:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Anti-pattern: duplicates the entire 150 MB JAR in a second layer
FROM eclipse-temurin:25-jre-alpine
WORKDIR /app

# Layer 1: copied as root (~150 MB)
COPY target/application.jar /app/app.jar

# Layer 2: chown triggers copy-on-write (~150 MB duplicated)
RUN addgroup -g 1001 -S appgroup && \
    adduser -u 1001 -S -G appgroup appuser && \
    chown -R appuser:appgroup /app

USER appuser
ENTRYPOINT ["java", "-jar", "app.jar"]

OverlayFS layers are immutable. Even though chown only changes file metadata, Copy-on-Write copies the entire 150 MB JAR into the new layer, bloating your final image by the full size of your artifact.

flowchart TD
    subgraph Bad["RUN chown (OverlayFS bloat)"]
        B1["Layer 1: COPY app.jar (150 MB, root)"] --> B2["Layer 2: RUN chown -R (150 MB copy, appuser)"]
        B2 --> B3["Final size: 300+ MB"]
    end
    subgraph Good["COPY --chown (Single layer)"]
        G1["Layer 1: RUN adduser appuser"] --> G2["Layer 2: COPY --chown=1001:1001 app.jar (150 MB)"]
        G2 --> G3["Final size: 150 MB"]
    end
    style Bad fill:#ffebee,stroke:#c62828,stroke-width:1px
    style Good fill:#e8f5e9,stroke:#2e7d32,stroke-width:1px

The right pattern: COPY --chown and pre-created write paths

Use COPY --chown (supported since Docker 17.09) to set ownership atomically in the same layer, and pre-create any runtime directories your app writes to:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Recommended: non-root multi-stage Dockerfile with zero layer bloat
# Stage 1: Build stage
FROM eclipse-temurin:25-jdk-alpine AS builder
WORKDIR /build

COPY gradlew .
COPY gradle gradle
COPY build.gradle.kts settings.gradle.kts ./
RUN chmod +x gradlew && ./gradlew dependencies --no-daemon

COPY src src
RUN ./gradlew bootJar --no-daemon -x test

# Stage 2: Production runtime stage
FROM eclipse-temurin:25-jre-alpine AS runner
WORKDIR /app

# 1. Create the fixed-UID runtime user and group
RUN addgroup -g 1001 -S appgroup && \
    adduser -u 1001 -S -G appgroup -h /app appuser

# 2. Pre-create writable runtime directories (logs, heap dumps, Tomcat temp)
RUN mkdir -p /app/logs /app/tmp && \
    chown -R appuser:appgroup /app/logs /app/tmp

# 3. Copy the JAR with ownership set atomically
COPY --chown=appuser:appgroup --from=builder /build/build/libs/*.jar /app/app.jar

# 4. Drop root privileges
USER appuser:appgroup

EXPOSE 8080
ENTRYPOINT ["java", "-Djava.io.tmpdir=/app/tmp", "-jar", "app.jar"]

Setting ownership with COPY --chown=appuser:appgroup writes the target UID/GID into the layer as it’s created, so Docker never duplicates the file.


Blocking vulnerable images in CI with Trivy

Non-root isolation limits runtime damage, while CVE scanning stops known vulnerabilities in base images and libraries before they ever reach production.

Scanning locally with Trivy CLI

Trivy (by Aqua Security) scans both OS packages (Alpine, Debian, RedHat) and language dependencies (Maven/Gradle JARs, npm, pip, Go modules) in seconds.

For a quick local check:

1
2
# Basic vulnerability scan
$ trivy image myapp:latest

For a CI security gate, combine three flags so builds fail only on actionable, high-impact findings:

1
2
3
4
5
$ trivy image \
    --severity HIGH,CRITICAL \
    --ignore-unfixed \
    --exit-code 1 \
    myapp:latest
  • --severity HIGH,CRITICAL: Ignore Low/Medium noise and block only serious flaws.
  • --ignore-unfixed: Skip CVEs that have no upstream patch yet so they don’t stall releases indefinitely.
  • --exit-code 1: Return a non-zero exit code when any matching CVE is found, failing the CI job.

When not to use --ignore-unfixed blindly: Skipping unfixed CVEs keeps pipelines moving, but it shouldn’t hide a zero-day forever. Run a separate scheduled nightly scan without --ignore-unfixed that alerts your team without blocking deploys.

Here is what a failing Trivy scan looks like on a Spring Boot JAR:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2026-06-09T14:32:00Z  INFO  Vulnerability scanning is enabled
2026-06-09T14:32:01Z  INFO  Detected OS: alpine (3.20.0)
2026-06-09T14:32:02Z  INFO  Number of language-specific files: 1
2026-06-09T14:32:02Z  INFO  Detecting jar vulnerabilities...

myapp:latest (alpine 3.20.0)
============================
Total: 0 (HIGH: 0, CRITICAL: 0)

app.jar (java-pkg)
==================
Total: 2 (HIGH: 1, CRITICAL: 1)

┌───────────────┬────────────────┬──────────┬────────┬───────────────────┬───────────────┬────────────────────────────────────────────┐
│    Library    │ Vulnerability  │ Severity │ Status │ Installed Version │ Fixed Version │                   Title                    │
├───────────────┼────────────────┼──────────┼────────┼───────────────────┼───────────────┼────────────────────────────────────────────┤
│ log4j-core    │ CVE-2021-44228 │ CRITICAL │ fixed  │ 2.14.1            │ 2.17.1        │ Remote Code Execution in Log4j             │
│ spring-core   │ CVE-2022-22965 │ HIGH     │ fixed  │ 5.3.17            │ 5.3.18        │ Spring Framework RCE via Data Binding      │
└───────────────┴────────────────┴──────────┴────────┴───────────────────┴───────────────┴────────────────────────────────────────────┘

Adding Trivy as a GitHub Actions gate

This workflow builds the image locally (load: true), scans it with Trivy, and only pushes to the registry if the scan exits 0:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
name: "Build and Security Scan"

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

jobs:
  build-and-scan:
    name: "Docker Build & Trivy Scan"
    runs-on: ubuntu-latest

    steps:
      - name: "Checkout repository"
        uses: actions/checkout@v4

      - name: "Set up Docker Buildx"
        uses: docker/setup-buildx-action@v3

      - name: "Build container image (load locally)"
        uses: docker/build-push-action@v6
        with:
          context: .
          load: true
          tags: myorg/backend-service:${{ github.sha }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

      - name: "Run Trivy CVE scan"
        uses: aquasecurity/trivy-action@master
        with:
          image-ref: 'myorg/backend-service:${{ github.sha }}'
          format: 'table'
          exit-code: '1'
          ignore-unfixed: true
          vuln-type: 'os,library'
          severity: 'CRITICAL,HIGH'

      - name: "Push to container registry"
        if: success()
        run: |
          echo "Security scan passed. Pushing production image..."
          # docker push myorg/backend-service:${{ github.sha }}
sequenceDiagram
    autonumber
    actor Dev as Developer (PR)
    participant CI as GitHub Actions Runner
    participant Trivy as Trivy Scanner
    participant Reg as Container Registry
    Dev->>CI: git push / open PR
    CI->>CI: Build multi-stage Docker image
    CI->>Trivy: Scan image (HIGH, CRITICAL)
    alt CVE found
        Trivy-->>CI: Exit code 1
        CI--xDev: Fail CI and block merge
    else Clean image
        Trivy-->>CI: Exit code 0
        CI->>Reg: Push verified image
    end

Production container security checklist

Before pushing a new service image to production, verify these five items:

  1. Verify USER is non-root: Run docker inspect --format='{{ .Config.User }}' <image> and confirm it prints your fixed non-root user or UID (not empty or 0).
  2. Replace RUN chown with COPY --chown: Prevent OverlayFS from duplicating large JARs across layers.
  3. Strip extra shells and network tools: Avoid shipping curl, wget, netcat, or package managers in your final runtime stage—consider Google Distroless images when you don’t need a shell.
  4. Never enable privileged: true: Keep privileged disabled in compose.yaml and Kubernetes manifests.
  5. Gate pushes with Trivy in CI: Fail builds on fixable HIGH and CRITICAL CVEs, and run a nightly scan without --ignore-unfixed to catch emerging zero-days.
This post is licensed under CC BY 4.0 by the author.