Container Security, Ethics and GovernanceIntroduction and ContextContainerization improves portability, deployment speed and operational consistency, but it does not automatically make software secure. A container is a process isolated by operating-system mechanisms, including namespaces, control groups, capabilities and security profiles. The isolation boundary is valuable, yet it is not equivalent to a virtual machine boundary. Containers share the host kernel, and a weakness in the runtime, kernel, image, orchestration platform or application may affect other workloads. Container security therefore concerns the complete lifecycle: source code, dependencies, image construction, registry storage, deployment configuration, runtime behaviour, monitoring, incident response and disposal. Governance extends this technical view by defining who may perform actions, which evidence must be retained, how risks are accepted, and how legal, ethical and organisational obligations are met. The central principle is least privilege: every process, user, service account and pipeline should receive only the permissions required for its legitimate task, for only as long as those permissions are needed. This principle must be combined with defence in depth, secure defaults, verifiable supply chains and continuous review. Learning ObjectivesBy the end of this chapter, a learner should be able to: - Explain the security boundary and threat model of containers.
- Apply least-privilege, non-root and rootless execution.
- Control Linux capabilities, seccomp and related security mechanisms.
- Protect secrets throughout development, delivery and runtime operations.
- Harden container images and evaluate software supply-chain risks.
- Describe policy enforcement, compliance evidence and governance responsibilities.
- Identify licensing, privacy, ethical and responsible-use implications.
- Analyse a container-security incident and recommend proportionate controls.
1. The Container Security ModelA container normally consists of an image, a runtime-created container process, a filesystem view and configuration supplied by a platform. Security depends on all of these elements. An application may be safe in isolation but become dangerous if its image contains vulnerable packages, its container runs as root, its socket is mounted, or its service account can access unrelated resources. A useful threat model considers the following assets: - application data and credentials;
- host operating systems and kernel interfaces;
- registries, build systems and source repositories;
- customer privacy and business continuity;
- intellectual property and licensed components; and
- audit records and security evidence.
Threat actors may include external attackers, malicious insiders, compromised dependencies, careless operators and automated processes with excessive permissions. Typical attack paths include exploiting an application vulnerability, escaping a container, abusing a mounted host path, stealing registry credentials, modifying an image, or using a legitimate service account for an unintended purpose. Container security is often described in layers: | Layer | Main concern | Representative controls |
|---|
| Code and dependencies | Vulnerable or malicious software | Review, testing, dependency scanning | | Image | Unsafe packages and configuration | Minimal base image, pinning, signing, scanning | | Registry and delivery | Tampering or unauthorised access | Authentication, access control, provenance | | Runtime | Excessive process authority | Non-root user, capabilities, seccomp, read-only filesystem | | Platform | Host and orchestration exposure | Patching, isolation, admission policy, network controls | | Governance | Accountability and compliance | Ownership, risk assessment, logs, review and response |
No single control is sufficient. A vulnerability scanner may identify a vulnerable package but cannot determine whether a compromised credential is exposed through an environment variable. Conversely, a read-only filesystem reduces persistence but does not prevent exploitation of a network-facing application. 2. Least Privilege and IdentityLeast privilege applies to human users, build agents, containers, orchestrators and applications. In Docker, the default user specified by an image may be root unless the image changes it. Root inside a container is not identical to unrestricted host root, because namespaces and other controls constrain it; nevertheless, a container process running as root has more authority than necessary for many workloads and may exploit runtime or kernel weaknesses more effectively. A Dockerfile should normally create a dedicated user and switch to it: FROM python:3.12-slim
WORKDIR /app
COPY --chown=app:app requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY --chown=app:app . .
USER app
CMD ["python", "server.py"] The exact user-management commands vary by base image. File ownership must be checked carefully: changing USER without ensuring access to the application directory can cause failures, while granting broad write permissions merely to fix a deployment error weakens security. A non-root container is not the same as rootless Docker. Non-root execution means the process inside the container uses an unprivileged user. Rootless mode means the Docker daemon and containers run without a root daemon on the host, typically using user namespaces and subordinate user identifiers. Rootless mode reduces the impact of daemon compromise and misconfiguration, although it can impose limitations involving networking, storage, performance and kernel support. These are complementary controls, not alternatives. Least privilege also requires limiting: - mounted host directories;
- access to the Docker socket;
- Linux capabilities;
- network destinations and listening ports;
- service-account permissions;
- registry operations; and
- CI/CD permissions and signing keys.
The Docker socket deserves special attention. Mounting /var/run/docker.sock gives a container access to the Docker daemon. Depending on daemon permissions, this may allow creation of privileged containers or access to host resources. A container that requires Docker control should use a carefully designed alternative, such as a restricted API, a dedicated build service or a rootless builder, rather than exposing the host socket by default. 3. Capabilities, Privileged Mode and SeccompLinux traditionally divides superuser authority into capabilities. Examples include NET_BIND_SERVICE, which permits binding to ports below 1024, and CHOWN, which permits ownership changes. Docker containers receive a reduced capability set compared with a fully privileged host process, but the default set may still exceed application requirements. A strong runtime pattern is to drop all capabilities and add back only those that are justified: docker run --rm \
--cap-drop=ALL \
--cap-add=NET_BIND_SERVICE \
--read-only \
--tmpfs /tmp:rw,noexec,nosuid,size=64m \
example/web:1.4 This example is appropriate only if the application genuinely needs the added capability. In many cases, changing the service to listen on an unprivileged port is safer than adding NET_BIND_SERVICE. --privileged should not be used as a general solution to permission errors. It significantly relaxes isolation and may expose devices and capabilities that are unnecessary for normal application workloads. If a system-management container requires special authority, it should be isolated, documented, monitored and approved as an exception.
Seccomp, short for secure computing mode, restricts the system calls a process may make. Docker commonly applies a default seccomp profile that blocks or filters dangerous calls. A custom profile can reduce the allowed system-call surface, but an overly restrictive profile may break legitimate applications. The correct process is to understand application behaviour, test in a non-production environment, begin with a documented baseline and review exceptions. Seccomp is not a substitute for patching. If an application is vulnerable, blocking some system calls may reduce exploitability but does not repair the defect. Other complementary mechanisms include AppArmor or SELinux policies, read-only filesystems, user namespaces and resource limits. 4. Filesystems, Networking and Runtime ResilienceA container filesystem should be treated as disposable unless persistence is explicitly required. A read-only root filesystem limits an attacker’s ability to modify binaries, install tools or create persistent files. Applications that need temporary storage can use a narrowly scoped temporary filesystem or a dedicated volume with appropriate ownership and permissions. Sensitive host paths should not be mounted into containers. When a volume is necessary, the organisation should document whether it is read-only, which data it contains, who owns it and how it is backed up and deleted. Device access should be denied unless technically essential. Network controls should follow application need rather than convenience. Containers should expose only required ports, and east-west communication should be restricted through networks, firewalls or orchestration policies. Administrative interfaces should not be exposed publicly. Egress restrictions are also important: a compromised service should not automatically be able to contact every internal system or upload data to arbitrary destinations. Resource limits are security and availability controls. CPU, memory, process-count and restart limits can reduce denial-of-service effects. They do not eliminate all resource-exhaustion risk, because shared hosts and orchestration layers may have additional limits and scheduling behaviour. Monitoring should detect abnormal process creation, memory use, network connections, image changes and privilege requests. 5. Secret ProtectionSecrets include passwords, API tokens, private keys, database credentials, signing keys and session secrets. They should not be committed to source control, embedded in images, written in Dockerfiles, or placed in public build logs. Docker image layers can preserve deleted files, so copying a secret into one layer and deleting it in a later layer does not reliably remove it from the image history. Environment variables are convenient but are not automatically secure. They may appear in process inspection, diagnostic output, crash reports or platform metadata. A suitable secret-management mechanism should provide controlled retrieval, encryption at rest and in transit, access auditing, rotation and revocation. Examples include an enterprise secret manager, an orchestrator’s secret facility or a short-lived identity-based token. A sound secret lifecycle includes: - classification of the secret and its owner;
- secure creation and distribution;
- minimum necessary access;
- monitoring and audit;
- rotation at defined intervals or after suspected exposure; and
- revocation and verified destruction.
Build-time secrets require particular care. Package managers may need credentials to access private repositories, but credentials should be supplied through ephemeral build-secret mechanisms rather than ordinary ARG or ENV instructions. The resulting image should contain only the application artefacts required at runtime. 6. Image Hardening and Software Supply ChainsAn image is executable supply-chain material. Its security depends on the base image, operating-system packages, language dependencies, build instructions and provenance. Image hardening begins with a maintained, minimal base image appropriate to the workload. “Minimal” does not mean “automatically secure”; an extremely small image can lack diagnostics, and an unmaintained minimal image may be riskier than a supported standard image. Recommended practices include: - use trusted and maintained base images;
- pin versions or immutable digests where reproducibility matters;
- remove package-manager caches and unnecessary tools;
- use multi-stage builds so compilers and test tools are excluded from runtime images;
- run vulnerability scans for operating-system and application dependencies;
- generate a software bill of materials (SBOM);
- sign images and verify signatures or attestations at deployment;
- rebuild regularly to obtain security fixes; and
- retain provenance showing source, builder, inputs and review.
A multi-stage build separates compilation from execution: FROM golang:1.22 AS build
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 go build -o /out/service ./cmd/service
FROM gcr.io/distroless/static-debian12
COPY --from=build /out/service /service
USER 65532:65532
ENTRYPOINT ["/service"] This pattern reduces the runtime image’s tools and attack surface. It does not guarantee safety: the source, dependencies, compiler image and final base image still require review. Vulnerability management requires interpretation rather than blind reaction. A scanner’s severity score is evidence, not a complete risk decision. Teams should consider exploitability, exposure, privileges required, compensating controls, available fixes and business impact. False positives and vulnerabilities in unreachable code require documented handling, while a lower-scored vulnerability actively exposed on a critical service may deserve urgent treatment. 7. Policy Enforcement and GovernanceSecurity policy becomes effective when it is translated into enforceable controls. A policy may require that images come from approved registries, run as non-root, avoid privileged mode, contain an SBOM, use signed provenance and define resource limits. Admission controls in a container platform can reject deployments that violate these requirements. Governance should define: - asset and service ownership;
- approved base images and registries;
- vulnerability remediation timeframes;
- exception approval and expiry;
- secret-management responsibilities;
- logging and evidence retention;
- incident escalation; and
- periodic review of controls.
A useful separation is between policy, standard and procedure. Policy states the organisational requirement, such as “production workloads must use least privilege.” A standard specifies measurable expectations, such as “containers must not run as UID 0 unless an approved exception exists.” A procedure explains how engineers build, test, deploy and document compliance. Governance must avoid becoming a purely bureaucratic exercise. Controls should be risk-based, automated where possible and designed with developer participation. A policy that cannot be applied consistently encourages workarounds. Exceptions are sometimes legitimate, but they should identify the reason, risk owner, compensating controls, review date and conditions for removal. Compliance frameworks may require access control, vulnerability management, change control, data protection, audit logging and incident response. Compliance evidence can include signed image attestations, scan results, deployment-policy decisions, access reviews, training records and incident exercises. Compliance does not prove that a system is secure; it demonstrates that specified controls and processes exist and are being followed. 8. Licensing, Privacy and Responsible UseContainer images commonly combine software from many licences. A production image may contain an application, operating-system packages, language libraries, fonts, certificates and build tools, each with licensing obligations. Organisations should maintain an SBOM and review licence compatibility before distribution. Some licences require notices, attribution, source availability or disclosure of modifications. Removing copyright and licence files is not an acceptable image-hardening technique. Privacy applies to both application data and operational data. Logs, environment variables, crash dumps and diagnostic bundles may contain personal data or secrets. Data minimisation, purpose limitation, access control, retention limits, encryption and appropriate deletion should be designed into container operations. Images should not contain customer data, production database dumps or personal identifiers used for convenience in testing. Ethical security practice requires authorised testing. Security teams must define scope, protect personal information, avoid unnecessary service disruption and report findings responsibly. Techniques such as privilege escalation, network scanning and exploit testing may be legitimate in an approved environment but harmful or unlawful when performed without authorisation. Automation and AI tools create additional governance questions. An AI assistant may generate Dockerfiles, policies or remediation advice, but generated content must be reviewed. Sensitive source code, credentials and personal data should not be submitted to an unapproved service. Security decisions should remain accountable to identified professionals, especially where automated systems could deny access, quarantine workloads or affect customers. 9. A Practical Security LifecycleA professional workflow integrates security into each stage: Plan. Identify assets, trust boundaries, data classifications and regulatory obligations. Define security acceptance criteria. Develop. Review dependencies, use secure coding practices and prevent secrets from entering repositories. Build with controlled and reproducible tooling. Verify. Test functionality, dependencies, image configuration, permissions, capabilities, secrets, provenance and policy compliance. Release. Sign approved images, record provenance, publish SBOMs and deploy only from controlled registries. Run. Enforce non-root and capability restrictions, monitor behaviour, patch hosts and images, restrict network access and back up required data. Respond. Detect, contain, investigate and recover from incidents. Preserve evidence and rotate credentials when exposure is possible. Improve. Review incidents, exceptions, metrics and emerging threats. Retire obsolete images and access rights. Security metrics should support decisions. Examples include the percentage of production images with verified provenance, the age of unresolved critical findings, the proportion of workloads running as non-root, secret-rotation compliance and time to revoke compromised credentials. Metrics must be interpreted carefully; a high scan-completion rate does not demonstrate that vulnerabilities are being fixed. 10. Illustrative Case: Compromised Build CredentialBackgroundA fictional online retailer, Northstar Retail, uses Docker images for its order-processing service. A CI job builds images and pushes them to a registry. To download private dependencies, the job stores a long-lived package-registry token in a Dockerfile argument. ProblemA developer notices that the token appears in build logs and may also exist in an intermediate image layer. An attacker later obtains the token from archived CI output and downloads private packages. The attacker cannot immediately deploy to production because the registry requires signed images, but the organisation must investigate whether intellectual property or customer data was exposed. AnalysisThe primary failure is not simply “a secret was visible.” Several governance and technical weaknesses interacted: - a long-lived credential was used where an ephemeral credential was possible;
- build logs had excessive retention and access;
- secret-scanning controls did not cover build output;
- the image-build process did not use secret mounts;
- the token’s permissions allowed more than package download; and
- rotation responsibilities were unclear.
Approach and SolutionNorthstar first revoked the token, issued a narrowly scoped replacement and reviewed registry and package-service logs. It identified affected builds and rebuilt images without the credential. The pipeline was changed to use an ephemeral secret available only during the dependency-fetch step. The final image was checked to confirm that no credential, private package cache or diagnostic output remained. The organisation then introduced secret scanning for source, Dockerfile instructions and CI logs; reduced log retention for sensitive build steps; restricted CI identities; required signed provenance; and documented an incident-response playbook. It also reviewed all other pipelines for similar patterns. OutcomeThe investigation found unauthorised package downloads but no evidence that production images were modified. The incident was classified as a supply-chain exposure and used as evidence for improving controls. The organisation did not claim that signing alone had prevented compromise; rather, signing limited the attacker’s ability to introduce an unapproved production image. Learning Points- Secrets can persist in logs and image layers even after deletion from the visible Dockerfile.
- Short-lived, narrowly scoped identities reduce blast radius.
- Provenance and signing are valuable only when deployment verifies them.
- Incident response should include credential rotation, evidence preservation and scope analysis.
- Governance failures often connect several individually small technical weaknesses.
11. Challenges and LimitationsContainer security is constrained by complexity. Images contain transitive dependencies that change over time, and vulnerability databases may be incomplete or inconsistent. A patched image may still be vulnerable through application logic, configuration or an external service. Rootless execution can be difficult for workloads requiring special networking or device access. Custom seccomp and MAC policies demand expertise and testing. Security controls can also create operational friction. Strict admission policies may block emergency fixes, while excessive scanning can produce alert fatigue. The appropriate response is not to disable controls but to improve prioritisation, provide secure development paths and make exceptions visible and temporary. Finally, containers do not remove the need for host, network, identity and organisational security. A well-hardened image deployed on an unpatched host with an exposed management interface remains at risk. Effective security is an engineered system of interdependent controls. Best-Practice ChecklistBefore production deployment, confirm that: - the image uses a maintained and appropriate base;
- dependencies and image contents have been scanned and reviewed;
- an SBOM and provenance record are available;
- the image is signed and deployment verifies the signature;
- the container runs as a non-root user where feasible;
- unnecessary capabilities are dropped;
- privileged mode and host socket mounts are absent or approved;
- the root filesystem is read-only where practical;
- secrets are retrieved through an approved mechanism;
- network ingress and egress are restricted;
- resource limits and monitoring are configured;
- licence and privacy reviews are complete; and
- ownership, exceptions and incident contacts are documented.
Chapter SummaryContainer security is a lifecycle and governance discipline, not merely an image-scanning activity. The strongest foundation is least privilege: run applications as non-root users, prefer rootless operation where appropriate, drop unnecessary capabilities and avoid privileged mode. Seccomp, MAC policies, read-only filesystems, network restrictions and resource limits provide defence in depth. Images should be minimal but maintained, reproducible, scanned, documented with an SBOM and protected by signing and provenance verification. Secrets must be excluded from source, image layers and logs, while short-lived, narrowly scoped credentials reduce exposure. Policy enforcement converts organisational expectations into repeatable deployment decisions, and compliance evidence supports accountability without replacing engineering judgement. Licensing, privacy and responsible-use principles are integral to professional practice. Container platforms process software, data and authority; therefore technical controls must be connected to ownership, review, incident response and ethical decision-making. Key TermsLeast privilege: Giving an identity only the authority required for an authorised task. Non-root execution: Running a container process as a user other than UID 0. Rootless mode: Operating the container engine and workloads without a root daemon on the host. Linux capability: A discrete unit of traditionally superuser authority. Seccomp: A mechanism for restricting the system calls available to a process. Privileged container: A container launched with substantially relaxed isolation and elevated host-related authority. Attack surface: The set of interfaces, components and privileges that may be targeted. Secret: Sensitive authentication or cryptographic material, such as a password or private key. Image layer: A filesystem change recorded as part of a container image. Base image: The foundational image from which another image is built. Multi-stage build: A build using separate stages so build tools need not enter the runtime image. SBOM: A software bill of materials listing components and dependencies in an artefact. Provenance: Evidence describing how, from what inputs and by which process an artefact was produced. Image signing: Applying a verifiable cryptographic signature to an image or its metadata. Admission control: A policy decision that allows or rejects a workload before deployment. Capability drop: Removal of Linux capabilities from a container process. Data minimisation: Collecting, exposing and retaining only the data needed for a legitimate purpose. Exception: An authorised, documented deviation from a security requirement. Supply-chain security: Protection of software components, tools, identities and processes from source to deployment. Review QuestionsShort Answer Questions- Why is a container running as root considered higher risk than one running as a dedicated unprivileged user?
- What is the difference between non-root execution and rootless Docker?
- Why should Docker socket mounts be treated as sensitive?
- Give two reasons that environment variables are not automatically secure secret storage.
- What information can an SBOM provide?
Long Answer Questions- Explain how capabilities, seccomp, read-only filesystems and network restrictions work together as defence in depth.
- Describe a secure container-image lifecycle from source development through production deployment.
- Discuss why vulnerability severity scores should not be used as the sole basis for remediation priority.
- Explain how licensing and privacy obligations affect container-image construction and operations.
- Design a governance model for approving, monitoring and retiring exceptions to container-security policy.
Analytical / Application Questions- A service fails after all Linux capabilities are dropped. Describe a systematic method for determining whether a narrowly scoped capability is genuinely required, and identify safer alternatives that should be considered first.
- A CI pipeline stores a private package token in an image build argument and retains logs for one year. Analyse the risks and propose technical, procedural and governance controls.
- An organisation has signed images but does not verify signatures at deployment. Evaluate what security benefit remains and design a control sequence that makes signing meaningful.
Multiple Choice Questions with AnswersQuestion 1Which practice most directly applies the principle of least privilege to a container? A. Running every container in privileged mode B. Dropping all unnecessary capabilities C. Mounting the host filesystem read-write D. Sharing the Docker socket with the application Correct Answer: B. Dropping all unnecessary capabilities Question 2What is the key distinction between a non-root container and rootless Docker? A. Non-root concerns the container process; rootless concerns the engine and daemon privilege B. They are exactly the same control C. Rootless requires every application to run as UID 0 D. Non-root execution disables image scanning Correct Answer: A. Non-root concerns the container process; rootless concerns the engine and daemon privilege Question 3Why is copying a secret into one image layer and deleting it in a later layer unsafe? A. Deletion always corrupts the image B. The earlier layer may still contain the secret C. Secrets can only be stored in volumes D. Docker automatically publishes the secret to all users Correct Answer: B. The earlier layer may still contain the secret Question 4What does seccomp primarily restrict? A. Container image size B. Network bandwidth C. System calls available to a process D. Software licence types Correct Answer: C. System calls available to a process Question 5Which Dockerfile practice reduces the number of build tools in a runtime image? A. Using a multi-stage build B. Running the final image as privileged C. Copying the entire build environment into production D. Storing credentials in ENV instructions Correct Answer: A. Using a multi-stage build Question 6What is the main purpose of an SBOM? A. To provide a list of software components and dependencies B. To replace all access-control policies C. To make a container run without a kernel D. To encrypt every application request Correct Answer: A. To provide a list of software components and dependencies Question 7Which statement about image signing is correct? A. Signing repairs vulnerabilities in application code B. Signing is useful only when deployment verifies the signature C. Signing removes all licensing obligations D. Signing makes root execution safe Correct Answer: B. Signing is useful only when deployment verifies the signature Question 8Which action best protects a compromised service from unrestricted internal access? A. Allowing all outbound traffic B. Restricting network ingress and egress to required destinations C. Mounting more host directories D. Disabling audit logs Correct Answer: B. Restricting network ingress and egress to required destinations Question 9Why should a long-lived CI credential generally be replaced with a short-lived, narrowly scoped identity? A. It increases the credential’s blast radius B. It reduces the time and authority available to an attacker C. It prevents all dependency vulnerabilities D. It eliminates the need for incident response Correct Answer: B. It reduces the time and authority available to an attacker Question 10Which is an ethical and governance requirement for security testing? A. Testing any public system without permission B. Defining authorised scope and protecting collected data C. Publishing credentials to prove a vulnerability D. Ignoring service disruption during testing Correct Answer: B. Defining authorised scope and protecting collected data
|