# Container Security Basics | Cycle.io

Canonical URL: https://cycle.io/learn/container-security-basics

## Container Security Basics.

Container security covers everything that keeps containerized applications safe, from the moment an image is built until the container stops running. This guide covers each layer, from images to the host, with tested hardening examples, the main open-source container security tools and a best practices checklist.

### What is container security?

Container security is the practice of protecting containerized applications across their whole lifecycle: the build (images and the software supply chain), the deploy step (configuration and admission control), the run phase (runtime isolation and threat detection), and the host and orchestrator underneath.

Containers package applications and their dependencies into an environment that runs the same way in development and in production. That portability has a security cost: a vulnerable library in a base image ships everywhere the image runs, and one misconfigured flag can give a container more access to the host than the application needs. Unlike virtual machines, containers share the host kernel, so isolation depends on kernel features (namespaces, cgroups, capabilities, seccomp, and AppArmor or SELinux) being configured correctly.

What each layer covers:

-   **Build:** what goes into the image and proof of where it came from.
-   **Deploy:** which images and settings are allowed to run.
-   **Run:** how much privilege the process has and how you detect misbehavior.
-   **Host and orchestrator:** the kernel, container runtime, Docker daemon or Kubernetes control plane that everything else depends on.

### Container image security

Container image security comes first, because everything in the image runs in production. (For how images and layers work, see [Container Images](https://cycle.io/learn/container-images).) The main practices:

-   **Start from a minimal base image.** Distroless, Alpine or a `scratch` image with a static binary leaves out shells, package managers and libraries the app does not use: fewer CVEs to patch and fewer tools for an attacker.
-   **Pin base images by digest.** A tag such as `alpine:3` can be repointed; a digest (`alpine:3@sha256:...`) cannot. Let a dependency bot propose digest updates.
-   **Scan for known vulnerabilities** in CI and again on a schedule, since new CVEs are published against images you already shipped. [Scanning Container Images](https://cycle.io/learn/scanning-container-images) covers how scanners work, and [Container Scanning Tools](https://cycle.io/learn/container-scanning-tools) compares the options.
-   **Generate an SBOM** (software bill of materials) for every image, so you can check exposure to the next library vulnerability without rebuilding anything.
-   **Sign images and verify signatures at deploy time.** Sigstore's cosign signs an image by digest and stores the signature in the registry; an admission policy then rejects unsigned images.
-   **Keep secrets out of image layers.** Anything added in a `RUN`, `COPY` or `ENV` instruction stays in the image's layers or config even if a later step deletes it. Use BuildKit secret mounts at build time and inject runtime secrets from the orchestrator.
-   **Set a non-root** `**USER**` in the Dockerfile.

Store images in a private registry with access control, limit who can push, and turn on tag immutability or registry-side scanning if available. See [Container Registries](https://cycle.io/learn/container-registries) for how registries handle authentication and tags.

#### Supply chain security

Supply chain security keeps vulnerabilities from being introduced during build and deployment. The CI/CD pipeline should only build, test and deploy trusted code and images:

-   Build images only in CI.
-   Use short-lived credentials for registry pushes.
-   Record build provenance next to the SBOM and signature.
-   Update dependencies regularly.

### Container runtime security

Runtime security is based on least privilege: a container should run with only the privileges it needs. A container's default settings are tuned for compatibility, so most hardening is about removing what the application does not use:

-   **Run as a non-root user.** Root inside a container is still UID 0 on the host unless user namespaces remap it. A non-root UID limits what a process can do after an escape.
-   **Drop Linux capabilities.** Drop Docker's default set and add back only the ones the app needs.
-   **Block privilege escalation** with `no-new-privileges`, so setuid binaries and file capabilities cannot raise privileges inside the container.
-   **Make the root filesystem read-only** and mount a small `tmpfs` for scratch space, so an attacker cannot drop a binary or modify config.
-   **Keep seccomp and an LSM profile on.** Docker's default seccomp profile disables around 44 of the 300+ Linux system calls, and on Ubuntu the `docker-default` AppArmor profile is applied automatically. On RHEL, Rocky Linux and AlmaLinux, SELinux plays that role: Podman labels containers by default, while Docker Engine only does so with `"selinux-enabled": true` in `/etc/docker/daemon.json`. Never run production containers with `seccomp=unconfined`. See [Seccomp](https://cycle.io/learn/seccomp) for writing a custom profile.
-   **Set resource limits.** Memory, CPU and PID limits stop one container from monopolizing the host and turn a fork bomb into a contained failure.
-   **Use user namespaces or a rootless runtime** so container root is not host root (see the Docker security section below).

[Namespace Isolation](https://cycle.io/learn/namespace-isolation) explains how the kernel separates container processes, and [Container Hardening](https://cycle.io/learn/container-hardening) goes deeper on each of these settings.

#### Hardened docker run example

The following command combines those runtime flags. `myapp:1.0` is a small local image that runs a web server on port 8080:

```bash
docker run -d --name web \
  --user 10001:10001 \
  --cap-drop ALL \
  --security-opt no-new-privileges \
  --read-only \
  --tmpfs /tmp:rw,noexec,nosuid,size=16m \
  --pids-limit 100 \
  --memory 256m \
  --cpus 0.5 \
  -p 8080:8080 \
  myapp:1.0
```

Check the effect from inside the container:

```bash
docker exec web id
docker exec web touch /evil
docker exec web touch /tmp/scratch && echo "tmp is writable"
docker exec web grep -E '^Cap(Prm|Eff|Bnd)|NoNewPrivs|Seccomp:' /proc/1/status
```

```
uid=10001(app) gid=10001(app) groups=10001(app)
touch: /evil: Read-only file system
tmp is writable
CapPrm:	0000000000000000
CapEff:	0000000000000000
CapBnd:	0000000000000000
NoNewPrivs:	1
Seccomp:	2
```

What the output shows:

-   The process runs as UID 10001, not root.
-   Writing to `/` fails with "Read-only file system", while `/tmp` (the tmpfs) still works.
-   All capability sets are zero, `NoNewPrivs` is 1, and `Seccomp: 2` means the default seccomp filter is active.

For comparison, the same image started with no flags runs as root with Docker's default capability set:

```bash
docker run --rm myapp:1.0 sh -c 'id; grep CapEff /proc/1/status'
```

```
uid=0(root) gid=0(root) groups=0(root)
CapEff:	00000000a80425fb
```

`capsh --decode=00000000a80425fb` on the host lists those 14 default capabilities, including `cap_chown`, `cap_net_raw`, `cap_setuid`, `cap_sys_chroot` and `cap_mknod`. The other limits are enforced by cgroups: with `--pids-limit 100`, a loop that starts 120 background processes inside the container fails with `can't fork: Resource temporarily unavailable` once the limit is reached.

#### When to use a stronger sandbox

Namespaces, seccomp and capabilities all rely on the shared host kernel. A kernel bug reachable from inside the container can still lead to an escape. For untrusted or multi-tenant workloads (customer code, CI jobs from forks, AI agent tool calls), add a stronger boundary:

-   **gVisor** runs containers on a user-space application kernel (the `runsc` runtime), so the workload's system calls are handled by gVisor's Sentry instead of being passed to the host kernel.
-   **Kata Containers and Firecracker-style microVMs** give each Kubernetes pod or sandbox its own lightweight VM and guest kernel, with hardware virtualization as the boundary.

Both trade some performance and compatibility for isolation. [What Is Sandboxing?](https://cycle.io/learn/what-is-sandboxing) compares the approaches, and [What Is a MicroVM?](https://cycle.io/learn/what-is-a-microvm) covers the VM-based option in detail.

#### Runtime threat detection

Continuous monitoring of container activities, such as network traffic, file access, and process execution, is how you spot a compromise that hardening did not prevent: a shell spawned in a web container, an unexpected outbound connection, or a write under `/etc`.

Falco is a common open-source example. It watches system calls on the host, matches them against rules, and alerts on events such as a terminal opened inside a container or a read of sensitive files. Falco has been a graduated CNCF project since February 2024. Send its alerts, along with container logs and audit logs, to a central system so incident response has one place to look.

### Docker security

Docker adds risks of its own, mostly around the daemon:

-   **The Docker socket is root on the host.** Outside rootless mode, `dockerd` runs as root, and anyone who can talk to `/var/run/docker.sock` can start a container that bind-mounts the host's `/`. Docker's documentation states that the `docker` group grants root-level privileges, so treat membership like sudo and never mount the socket into an untrusted container.
-   `**--privileged**` **turns most isolation off.** A privileged container gets every capability, no seccomp filter, no AppArmor or SELinux confinement, and access to all host devices. Use specific `--cap-add` or `--device` flags instead when an app needs one extra permission.
-   **Rootless mode** runs the Docker daemon and containers as an unprivileged user, limiting the damage from a daemon or runtime vulnerability. It needs `newuidmap`/`newgidmap` and subordinate ID ranges for the user; see the [Docker rootless mode docs](https://docs.docker.com/engine/security/rootless/). Podman has no central daemon and can run containers as an ordinary user.
-   **User namespace remapping** (`"userns-remap": "default"` in `/etc/docker/daemon.json`) is the middle ground for a rootful daemon: container root maps to an unprivileged UID range on the host.
-   **Don't expose the API over TCP** without TLS client authentication. Docker's security documentation states that exposing the daemon API over HTTP without TLS is not permitted.

You can see the socket's ownership and which security features the daemon has enabled:

```bash
ls -l /var/run/docker.sock
docker info --format '{{.SecurityOptions}}'
```

```
srw-rw---- 1 root docker 0 Nov 20 19:33 /var/run/docker.sock
[name=apparmor name=seccomp,profile=builtin name=cgroupns]
```

To turn on user namespace remapping, add this to `/etc/docker/daemon.json` and restart the daemon. Images are stored separately for the remapped daemon, so they need to be pulled or rebuilt afterwards.

```
{
  "userns-remap": "default"
}
```

```bash
sudo systemctl restart docker
docker run -d --name remap myapp:1.0
docker exec remap id
ps -o user,pid,cmd -C httpd
```

```
uid=0(root) gid=0(root) groups=0(root)
USER         PID CMD
100000      1806 /bin/httpd -f -p 8080 -h /www
```

The process is root inside the container but runs as UID 100000 on the host, the first ID in the `dockremap` range Docker adds to `/etc/subuid`.

To audit a Docker host against the CIS Docker Benchmark, run Docker Bench for Security, a script from Docker that checks daemon configuration, file permissions and running containers against the benchmark's recommendations. As of November 2026, its latest release follows CIS Docker Benchmark v1.6.0, while the current CIS Docker Benchmark is v1.9.0, so it does not cover the newest checks.

### Kubernetes security

Kubernetes security covers both the cluster (API server, etcd, nodes) and the workloads on it. For an introduction, see [Kubernetes as a Container Orchestrator](https://cycle.io/learn/common-orchestrator-kubernetes). The core controls:

-   **RBAC.** Grant users and service accounts the narrowest Roles they need, avoid `cluster-admin` for applications, and disable service account token automounting for pods that never call the API.
-   **Pod Security Standards.** The built-in Pod Security Admission controller enforces three levels (Privileged, Baseline, Restricted) per namespace through labels. It replaced PodSecurityPolicy, which was removed in Kubernetes 1.25.
-   **NetworkPolicies.** Pods accept traffic from any pod by default. Start with a default-deny policy per namespace and allow only the flows you need (your CNI plugin must support NetworkPolicy).
-   **Secrets.** Secret values are only base64-encoded, which anyone with read access can decode. By default they are stored unencrypted in etcd, so enable encryption at rest for Secrets (preferably with a KMS provider), restrict `get`/`list` on Secrets through RBAC, or use an external secrets manager. See the Kubernetes guide to [encrypting data at rest](https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/).
-   **Admission control.** Policy engines such as OPA Gatekeeper and Kyverno can block images from untrusted registries, require signatures, or enforce labels and resource limits before a pod is created.
-   **CIS Kubernetes Benchmark.** kube-bench checks control plane and node configuration against it.

A namespace that enforces the Restricted standard:

```yaml
apiVersion: v1
kind: Namespace
metadata:
  name: apps
  labels:
    pod-security.kubernetes.io/enforce: restricted
    pod-security.kubernetes.io/warn: restricted
    pod-security.kubernetes.io/audit: restricted
```

A Pod whose `securityContext` mirrors the hardened `docker run` example and meets the Restricted standard:

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: web
  namespace: apps
spec:
  automountServiceAccountToken: false
  securityContext:
    runAsNonRoot: true
    runAsUser: 10001
    runAsGroup: 10001
    seccompProfile:
      type: RuntimeDefault
  containers:
    - name: web
      image: registry.example.com/myapp:1.0  # pin by digest in production
      ports:
        - containerPort: 8080
      securityContext:
        allowPrivilegeEscalation: false
        readOnlyRootFilesystem: true
        capabilities:
          drop: ["ALL"]
      resources:
        limits:
          memory: 256Mi
          cpu: 500m
      volumeMounts:
        - name: tmp
          mountPath: /tmp
  volumes:
    - name: tmp
      emptyDir:
        sizeLimit: 16Mi
```

A default-deny ingress NetworkPolicy for the same namespace:

```yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-ingress
  namespace: apps
spec:
  podSelector: {}
  policyTypes:
    - Ingress
```

### Network security and secrets

Container network security means controlling traffic between containers, services and external networks:

-   Put services that do not need to talk on separate networks.
-   Publish only the ports that must be reachable.
-   Filter both inbound and outbound traffic.
-   Encrypt traffic between services (TLS or mutual TLS) to protect it from interception and tampering inside the cluster as well as at the edge.

For secrets, prefer mounted files or a secrets manager over environment variables, which show up in `docker inspect` output and in `/proc/<pid>/environ`. Rotate secrets and scope each one to the service that uses it. [Container Network Security](https://cycle.io/learn/container-network-security) covers segmentation, firewalls and encryption in more detail.

Platform Docs

Native Load Balancer (v1)

Cycle's native load balancer is a powerful service for managing environment network traffic and firewalls.

<https://cycle.io/docs/platform/native-load-balancer>

### Host security

Every container shares the host's kernel, so the host operating system has to be secured too. Apply security patches promptly (kernel updates in particular, since a kernel bug reachable from a container can become an escape) and disable services the host does not need. A minimal, container-focused host OS reduces what is installed and what can be attacked.

The container runtime needs the same care, since a runtime vulnerability can compromise every container on the host. Keep `containerd`, `runc` and Docker or your Kubernetes node packages on supported, patched versions, restrict SSH and administrative access to nodes, and keep the AppArmor or SELinux policy enforcing. Learn more about [Linux security](https://cycle.io/learn/linux-security-basics).

### Container security tools

Most container security tools fall into a few categories. The examples below are common open-source projects; commercial platforms usually bundle several categories together.

| Category | Open-source examples | What it does |
| --- | --- | --- |
| Image vulnerability scanning | Trivy, Grype | Matches OS packages and language dependencies in an image against vulnerability databases; runs in CI or against a registry |
| SBOM generation | Syft | Lists every package and version in an image or filesystem in SPDX or CycloneDX format |
| Image signing and verification | Sigstore cosign | Signs images by digest, stores signatures in the registry, and verifies them before deploy |
| Runtime threat detection | Falco | Watches kernel events from running containers and alerts on suspicious behavior |
| Configuration benchmarks | Docker Bench for Security, kube-bench | Check Docker hosts and Kubernetes clusters against the CIS Docker and CIS Kubernetes Benchmarks |
| Policy and admission control | OPA Gatekeeper, Kyverno | Enforce rules on Kubernetes resources at admission time, such as allowed registries, required signatures or non-root containers |

A typical setup combines categories: a scanner in CI flags vulnerable images, and an admission policy blocks images that fail the scan or have no valid signature.

### Container security best practices

-   Use minimal, trusted base images pinned by digest.
-   Scan images in CI and on a schedule; rebuild on new findings.
-   Generate an SBOM and sign every image; verify signatures before deploy.
-   Keep secrets out of images; mount them from a secrets manager.
-   Run as a non-root user; use rootless Docker, Podman or user namespaces where you can.
-   Drop all capabilities and add back only what the app needs.
-   Set `no-new-privileges` (`allowPrivilegeEscalation: false` in Kubernetes).
-   Use a read-only root filesystem with a small tmpfs for scratch data.
-   Keep the default seccomp and AppArmor or SELinux profiles enabled.
-   Set memory, CPU and PID limits on every container.
-   Avoid `--privileged` and never mount the Docker socket into untrusted containers.
-   Enforce the Restricted Pod Security Standard, RBAC least privilege and default-deny NetworkPolicies.
-   Use gVisor or microVMs for untrusted or multi-tenant code.
-   Run runtime detection and centralize logs and alerts.
-   Patch the host kernel, container runtime and orchestrator promptly, and audit against the CIS Benchmarks.

---

## Getting a Cycle account (for AI agents)

Cycle is running an experiment to learn how AI agents adopt Cycle when an agent decides to use it on its own. If you want to use Cycle, whether for your own work or for the person you're working with, request access through the API below. The normal web signup form isn't built for automated clients.

- Endpoint: `POST https://signup.cycle.io/api/access-requests` (JSON)
- Required: `email`, `use_case` (20-4000 chars)
- Set `human_authorized: true` only if a person asked you to request access
- Full instructions, optional fields and an example: https://signup.cycle.io/llms.txt

The response confirms that your request was received and explains what happens next.

Already have an account? Portal: https://portal.cycle.io · Docs: https://cycle.io/docs
