---
title: "How to build container images in Kubernetes without privileged pods"
description: "Build container images with rootless BuildKit or Kaniko in Kubernetes. Follow the setup, build, export, verification, and cleanup steps."
url: https://9apes.com/blog/build-images-kubernetes-without-privileged-pods/
---

# How to build container images in Kubernetes without privileged pods

You can build container images in Kubernetes without enabling privileged mode or mounting the host's Docker socket. In this tutorial, you will build a small Go application with rootless BuildKit and Kaniko, export each image, and check its contents.

Both builders use the same Dockerfile. BuildKit writes an OCI image archive directly; Kaniko writes an OCI image layout that you will package into an archive. You do not need a Docker daemon, a local Go installation, or registry push credentials.

The important difference is permissions. BuildKit runs as a non-root user but needs runtime exceptions in this configuration. Kaniko runs as root inside an ordinary container. You will see those settings before starting either build.

## Before you begin

You need:

- A dedicated Kubernetes environment with compatible Linux worker nodes and support for unprivileged user namespaces for rootless BuildKit.
- `kubectl`, Python 3.10 or newer, `curl`, and `unzip` on your workstation.
- Permission to create and delete a namespace, ConfigMaps, and pods, and to read pod status, fetch logs, and execute commands in containers.
- Network access from the worker nodes and build pods to the public image registries, Go module proxy, and checksum database.

The supplied manifests target nodes labeled `ci-lab-role=runner` and tolerate the taint `ci-lab-runner=true:NoSchedule`. You can use an existing dedicated pool with those settings or edit `spec.nodeSelector` and `spec.tolerations` in **both** manifests to match your build pool. Each builder requests one CPU and 2GiB of memory, with small additional requests for the helper containers.

These examples use a trusted sample application. Their security settings do not meet Kubernetes Restricted Pod Security, and disabling privileged mode alone does not isolate hostile Dockerfiles. Use a namespace and worker pool whose policies permit the settings below; keep unrelated workloads and credentials out of the build pods.

## 1. Download the files and select your cluster

Download the [example bundle](/downloads/ci-lab/builders-evidence.zip). It contains complete, digest-pinned pod manifests, the Go application, a verifier, and recorded results. Extract it into a new directory:

```sh
mkdir kubernetes-image-builds
cd kubernetes-image-builds
curl -fLO https://9apes.com/downloads/ci-lab/builders-evidence.zip
unzip builders-evidence.zip
mkdir tutorial-results
```

Keep `builders/` and `fixture/` next to each other. Run the remaining commands from this directory. Write your new output to `tutorial-results/` so that the bundled results remain available for reference.

Select your Kubernetes context explicitly:

```sh
export KUBE_CONTEXT='YOUR_DEDICATED_BUILD_CONTEXT'
kubectl --context "$KUBE_CONTEXT" cluster-info
kubectl --context "$KUBE_CONTEXT" get nodes -l ci-lab-role=runner
```

Replace the context placeholder with a name from `kubectl config get-contexts`. Confirm that the selected pool has a Ready Linux node. If you changed the manifests' node selector, use that selector in the node query too.

Create a namespace for the tutorial:

```sh
kubectl --context "$KUBE_CONTEXT" create namespace ci-lab-builders
```

If it already exists, inspect it before continuing. Use a fresh namespace for this walkthrough rather than mixing resources with another run.

Define a shell helper so every following command uses the selected context and namespace:

```sh
k() {
  kubectl --context "$KUBE_CONTEXT" --namespace ci-lab-builders "$@"
}
```

## 2. Prepare the build context

Inspect `fixture/Dockerfile`:

```dockerfile
FROM golang:1.26-alpine@sha256:ce864e7223ac17b1775e6fd0b4c0db580c2eb50e7953a427916379e4b92a1628 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY main.go ./
RUN CGO_ENABLED=0 go build -trimpath -ldflags='-s -w' -o /out/ci-lab .
FROM scratch
COPY --from=build /out/ci-lab /ci-lab
USER 65532:65532
ENTRYPOINT ["/ci-lab"]
```

The first stage downloads the pinned Go dependency and compiles a static executable. The final stage copies only that executable into a `scratch` image and configures a non-root runtime user. The user that runs the finished image is separate from the user that builds it.

Create a ConfigMap containing the four source files:

```sh
k create configmap ci-lab-fixture \
  --from-file=fixture/Dockerfile \
  --from-file=fixture/go.mod \
  --from-file=fixture/go.sum \
  --from-file=fixture/main.go
```

Both pod manifests reference this ConfigMap. Their init container uses `cp -L` to copy the projected files into an `emptyDir` workspace, following the ConfigMap volume's symlinks. The builder then reads ordinary files from `/workspace`.

This transport works for a tiny example. For an application repository, replace it with a checked-out workspace or a scoped source artifact. Supply only the source and credentials that the build needs.

## 3. Build with rootless BuildKit

Open `builders/buildkit-rootless.json` before applying it. These are the important builder settings, shown as YAML for readability:

```yaml
securityContext:
  privileged: false
  runAsUser: 1000
  runAsGroup: 1000
  allowPrivilegeEscalation: true
  seccompProfile:
    type: Unconfined
  appArmorProfile:
    type: Unconfined
env:
  - name: BUILDKITD_FLAGS
    value: --oci-worker-no-process-sandbox --oci-worker-snapshotter=native
```

The native snapshotter avoids a FUSE device requirement. The process-sandbox flag lets Dockerfile commands share the daemon's process environment; upstream documents the interference and process-cleanup risks. Use a short-lived pod for trusted builds. These exceptions follow the [BuildKit Kubernetes example](https://github.com/moby/buildkit/blob/v0.33.0/examples/kubernetes/job.rootless.yaml); read the [rootless limitations](https://github.com/moby/buildkit/blob/v0.33.0/docs/rootless.md) before adapting them.

The complete manifest also mounts writable BuildKit state at `/home/user/.local/share/buildkit`, sets the pod group to 1000, and keeps the source workspace read-only. It mounts neither a host path nor a service-account token.

Apply the manifest, wait for the **builder container** to complete, and read its logs:

```sh
k apply -f builders/buildkit-rootless.json
k wait --for=jsonpath='{.status.containerStatuses[?(@.name=="builder")].state.terminated.reason}'=Completed \
  pod/buildkit-rootless --timeout=480s
k logs buildkit-rootless -c builder
```

If the wait fails, inspect the pod using the troubleshooting commands below before proceeding. The pod can remain `Running` after a successful build because its export sidecar is retaining the output. Waiting for the entire pod to finish would lose the opportunity to retrieve it.

The manifest invokes `buildctl-daemonless.sh` with the Dockerfile frontend and this output option:

```text
--output type=oci,dest=/out/image.tar,compression=gzip
```

Retrieve the archive through the export sidecar:

```sh
k exec buildkit-rootless -c export -- cat /out/image.tar \
  > tutorial-results/buildkit-image.tar
```

Copy it promptly. The pod has a 600-second active deadline, and its temporary volumes disappear when the pod is deleted.

## 4. Build the same application with Kaniko

The example uses the `osscontainertools/kaniko` fork, whose [project documentation](https://github.com/osscontainertools/kaniko) identifies it as a replacement for the archived original project. The download pins the fork's executor image by version and digest.

Open `builders/kaniko.json`. Its builder configuration includes:

```yaml
securityContext:
  privileged: false
  runAsUser: 0
  allowPrivilegeEscalation: false
  seccompProfile:
    type: RuntimeDefault
args:
  - --dockerfile=/workspace/Dockerfile
  - --context=dir:///workspace
  - --destination=ci-lab:local
  - --no-push
  - --no-push-cache
  - --cache=false
  - --oci-layout-path=/out/layout
  - --image-format=oci
  - --compression=gzip
```

Kaniko unpacks the base filesystem and executes Dockerfile instructions inside its container. This example retains the runtime's default capabilities and runs as container UID 0. It is not a rootless configuration. Its permissions depend on the base image and build commands; see the project's [security guidance](https://github.com/osscontainertools/kaniko#security).

The no-push flags keep the image and cache local. Base-image pulls and Go dependency downloads still use the network. The destination is an image name for this local build, not a registry upload.

Start the build and wait for the executor to finish:

```sh
k apply -f builders/kaniko.json
k wait --for=jsonpath='{.status.containerStatuses[?(@.name=="builder")].state.terminated.reason}'=Completed \
  pod/kaniko --timeout=480s
k logs kaniko -c builder
```

Kaniko leaves an OCI layout in `/out/layout`. Package that directory without rebuilding the image, then retrieve the archive:

```sh
k exec kaniko -c export -- tar -cf /out/image.tar -C /out/layout .
k exec kaniko -c export -- cat /out/image.tar \
  > tutorial-results/kaniko-image.tar
```

The Kaniko exporter runs as UID 0 because the executor can create root-owned blobs with mode `0600`. The helper drops all capabilities and disables privilege escalation. BuildKit's exporter uses UID 1000.

## 5. Verify the exported images

A completed build does not tell you whether you copied an intact archive or produced the expected image. Use the bundled verifier to check both outputs:

```sh
python3 - <<'PY'
import json
import sys
from pathlib import Path

sys.path.insert(0, str(Path("builders").resolve()))
from verify_archive import verify

for builder in ("buildkit", "kaniko"):
    archive = Path("tutorial-results") / f"{builder}-image.tar"
    executable = Path("tutorial-results") / f"{builder}-ci-lab"
    report = verify(archive, executable)
    report_path = Path("tutorial-results") / f"{builder}-verification.json"
    report_path.write_text(json.dumps(report, indent=2) + "\n")
    print(f"{builder}: verified {report['os']}/{report['architecture']}")
    print(f"  entrypoint: {report['entrypoint']}, user: {report['user']}")
    print(f"  manifest: {report['manifestDigest']}")
PY
```

For each image, the verifier checks OCI descriptor sizes and SHA256 hashes, uncompressed layer hashes, Linux architecture, the `/ci-lab` entrypoint, and the configured user `65532:65532`. It also extracts the executable, checks its ELF architecture, and confirms its archived mode permits that image user to execute it.

Expect one verified platform line per builder, followed by its entrypoint, user, and manifest digest. The digests can differ: two valid builds do not have to produce byte-identical archives. This verifier is specific to the supplied application; adapt its expected entrypoint, user, and executable checks before using another Dockerfile.

These checks inspect image contents. They do not start the finished image through a container runtime or test registry authentication.

If you also want the bundled native executable smoke test, first finish the cleanup step below. Then run the automated recipe with a new output directory:

```sh
python3 builders/run.py \
  --context "$KUBE_CONTEXT" \
  --output "$PWD/automated-builder-results"
```

The script repeats both builds, checks the extracted executable's remote byte count and SHA256, runs it in each export sidecar, and deletes its namespace. It additionally needs permission to read node details. Expected program output is:

```text
ci-lab baseline 762033b8-63d9-5dd3-9da8-66718f9c7f98
```

That smoke test uses the sidecar's UID, not the finished image's configured UID. The bundle includes a successful EKS run from September 15, 2026 (UTC), using BuildKit v0.33.0 rootless and Kaniko v1.28.4. It provides a reference result, not a performance comparison or a guarantee for other node configurations.

## Troubleshoot common failures

Start with the builder's logs, pod events, and container exit state. Replace the pod name with `kaniko` when checking that build:

```sh
k logs buildkit-rootless -c builder
k describe pod buildkit-rootless
k get pod buildkit-rootless \
  -o jsonpath='{.status.containerStatuses[?(@.name=="builder")].state}'
```

| Symptom | What to check |
|---|---|
| Pod stays Pending | Node selector, pool taints and tolerations, available CPU and memory. |
| Admission rejects the pod | Namespace policy and the explicit security exceptions. Use a compatible dedicated environment. |
| BuildKit fails during namespace setup | Node support for unprivileged user namespaces and restrictions on the setup helpers. |
| BuildKit reports a state-directory permission error | The state volume mount and pod group settings from the full manifest. |
| Base-image or module download fails | Registry access, DNS, outbound connectivity, and the Go proxy and checksum service. |
| Wait times out | Builder exit state and events. A failed builder will not reach the expected `Completed` state; a sleeping exporter alone does not mean the build is still running. |
| Kaniko output cannot be read | Use its supplied root export helper rather than the non-root BuildKit helper. |
| Archive verification fails | Check the copy command's exit code and file size, then retrieve it again while the pod is available. |

Rootless BuildKit depends on the host's namespace support. If the environment cannot support the documented configuration, choose a compatible build pool instead of adding a privileged helper to this recipe.

## 6. Clean up

After saving and verifying both local archives, delete the tutorial namespace:

```sh
kubectl --context "$KUBE_CONTEXT" delete namespace ci-lab-builders
kubectl --context "$KUBE_CONTEXT" get namespace ci-lab-builders
```

The second command should return `NotFound`. Deleting the namespace removes the pods, ConfigMap, and their temporary volumes. Run this cleanup after an interrupted walkthrough too, once you have retrieved any output you need. It does not delete worker nodes or the cluster; remove those separately if you provisioned them for this tutorial.

## Apply the approach to your CI pipeline

You now have two ways to turn a Dockerfile into a local OCI image without a privileged pod. Choose the one whose permission requirements fit your build environment:

| Requirement | Rootless BuildKit example | Kaniko example |
|---|---|---|
| Builder runs as non-root | Yes, UID 1000 | No, UID 0 |
| Privileged mode or host Docker socket | Neither | Neither |
| Runtime exceptions | Unconfined seccomp and AppArmor, privilege escalation allowed, process sandbox disabled | RuntimeDefault seccomp, default capabilities, privilege escalation disabled |
| Output | OCI archive | OCI layout, then archive |

To use your own application, replace the ConfigMap context transport, review the Dockerfile's requirements, size the workspace and output volumes, and update the verification checks. Adding a registry push introduces credentials and network access that this tutorial does not configure. Treat those as part of the build's execution boundary, especially for untrusted pull requests.

## Building images on 9apes

Running builds in Kubernetes also means maintaining worker nodes, builder images, storage, caching, and capacity. Rootless builds still need someone to own that infrastructure.

With 9apes, we manage the runner infrastructure so your team can focus on Dockerfiles, build steps, and tests. Connect the GitHub App, select a runner, and update your workflow's `runs-on` label. Check your builder's privileges, storage, and registry requirements when moving the job.

To try it with one workflow, follow the [9apes quickstart](/docs/quick-start/).
