Docker Security Best Practices: How to Secure Docker Containers and Images
Secure your Docker containers step by step: hardened images, Trivy scanning, secrets, runtime limits and daemon hardening — with a worked Flask example.
What Is Docker Security?
Docker security is the practice of protecting Docker images, running containers, and the hosts that run them. It combines trusted, patched images with least-privilege runtime settings, protected secrets, restricted networking, and tight control of the Docker daemon. The goal is to limit both what attackers can reach and what a compromised container can do.
How Docker Isolation Works
On Linux, Docker uses namespaces to give processes different views of system resources. The pid namespace isolates process IDs; net isolates network interfaces and routes; mnt controls which filesystems a process sees; uts scopes the hostname; and ipc isolates resources such as shared memory. A user namespace can map a container's user and group IDs to different IDs on the host. Rootless Docker and user namespace remapping use this capability; do not assume it is enabled on a default rootful daemon.
Control groups, or cgroups, account for and limit resources such as memory, CPU time, and process count. They help stop one workload from exhausting resources other workloads need. They do not decide which system calls a process may make or whether it can read a mounted file. Those are separate controls.
Containers are not virtual machines. Linux containers share the kernel of their Docker host. On a system where Docker runs inside a VM, the Linux containers share that VM's kernel. A kernel or runtime weakness can affect the isolation on which every container on that host depends.
What You Need to Secure
The commands below assume a patched Linux lab with Docker Engine, Buildx, and a shell. Use an isolated, disposable VM for the worked example and publish its web service only on loopback.
Why Docker Security Matters
A clean image scan does not make a privileged container safe. A well-confined process can still serve traffic through a vulnerable library. Use this table to identify which control addresses each kind of risk.
| Threat category | Examples | Control to apply |
|---|---|---|
| Image vulnerabilities | Known CVEs, outdated OS or application packages, embedded secrets | Minimize the image, scan the release candidate, and rebuild with fixes. Rotate any embedded credential. |
| Runtime threats | Excess capabilities, writable sensitive host mounts, unrestricted resource use | Run as non-root, drop capabilities, avoid host mounts, and set resource limits. |
| Daemon and host threats | An exposed Docker API or socket, unreviewed membership in the docker group, an unpatched runtime | Restrict daemon access, audit administrators, and apply host and runtime updates. |
| Supply-chain threats | Typosquatted image names, unsigned images where signatures are required, mutable tags | Verify the publisher, pin digests, and enforce your signature policy. |
Two historical, patched runc vulnerabilities illustrate why host updates matter. CVE-2019-5736 was a container breakout involving /proc/self/exe. CVE-2024-21626 was a container escape involving runc's handling of the working directory, including scenarios associated with Docker's --workdir setting. Neither is a lab exercise. The lesson is to verify that your host actually runs a patched runtime; rebuilding application images does not replace runc on the host.
docker version
docker info
uname -r
Check the server side of docker version, confirm which Docker context you are using, and compare your installed engine and runtime packages with your vendor's security advisories. Updating the CLI alone does not update the daemon it talks to.
How to Secure Docker Containers in 7 Steps: Docker Security Best Practices
Use these steps in order. Make the safe build repeatable before you tune runtime settings. The commands that reference flask-lab:hardened use the image built in the worked example below.
1. Choose a Minimal, Pinned Base Image
Pick the smallest maintained base that supports your application and your team's debugging and patching needs. Use a recognizable version tag and copy the real digest from the registry before building.
FROM python:3.11-slim-bookworm@sha256:<digest>
2. Write a Secure Dockerfile
Copy only the files your app needs and configure a numeric non-root identity in the final stage. Choose a UID and GID explicitly so the identity does not depend on the runtime image having a named user.
USER 10001:10001
3. Scan the Image You Built
Review vulnerability findings before promotion. Scan the final artifact rather than relying on a report for the base image, which does not cover the libraries your application added.
trivy image --severity HIGH,CRITICAL flask-lab:hardened
4. Keep Secrets Out of the Image
Pass build credentials through a BuildKit mount and give runtime credentials to the running service separately. This build command assumes the hardened Dockerfile and dummy token file from the example.
docker build --secret id=build_token,src=./build-token.txt -t flask-lab:hardened .
5. Run With Least Privilege
Drop capabilities and prevent processes from acquiring new privileges. This one-shot check verifies the image works under the intended UID without publishing a port.
docker run --rm --user 10001:10001 --cap-drop ALL --security-opt=no-new-privileges flask-lab:hardened /opt/venv/bin/python -c 'import os; assert os.geteuid() == 10001'
6. Lock Down the Network
Separate services that do not need to communicate. An internal network can isolate a backend tier from external routing through that network. Creating it is only the first step; attach just the intended services.
docker network create --internal backend-only
7. Harden the Daemon and Host
Review the daemon's security options, access controls, and patch status. Check the engine from the same context that deploys the workload, not just from a developer laptop.
docker context show
docker info --format '{{json .SecurityOptions}}'
Building Secure Docker Images
Choose a Base You Can Maintain
A smaller image often contains fewer packages to patch, but size alone is not a security measure. An image your team can rebuild quickly from a supported source is a better choice than a smaller image with unknown provenance.
| Base image type | What it offers | Trade-off to test |
|---|---|---|
| Alpine | A small Linux base with musl libc | Some Python wheels target glibc. You may need compatible wheels or a builder that compiles dependencies against musl. |
| Debian slim | A smaller Debian base with glibc, useful for many Python applications | It still contains OS packages that need patching. Check the support status of the named Debian release. |
| Distroless | Runtime-focused images at gcr.io/distroless, typically without a shell or package manager | Match the builder's output to the runtime's operating system and libraries. Plan to debug without opening a shell in the image. |
| Chainguard | Minimal, purpose-built images at cgr.dev/chainguard | Check that the image, tag, architecture, and runtime conventions meet your requirements. Test your scanner and debugging workflow. |
Use an official base or a publisher your organization has approved. Check the full repository name before you pull an image. A name that looks like a popular image is not proof that it comes from the same publisher.
Pin the Version and the Digest
A tag documents the version you intended to use. A digest fixes the content addressed by that reference, so moving the tag does not silently change the base of your next build.
docker buildx imagetools inspect python:3.11-slim-bookworm
Copy the real digest from the registry. Replace <digest> with the hexadecimal part after sha256:; do not copy the prefix twice. For a multi-platform image, distinguish the top-level index digest from an individual platform manifest digest. If you pin a platform manifest, make sure it matches your build target. Plan regular digest updates: pinning is a way to review changes, not a reason to defer patches. Adding --pull to a build does not switch a pinned digest to a newer one.
Use a Multi-Stage Build
Install dependencies in a builder and copy only the runtime output to the final stage. This Python template assumes requirements.txt and app.py are in the build context and that both placeholders have been replaced with the approved digest.
FROM python:3.11-slim-bookworm@sha256:<digest> AS build
WORKDIR /build
COPY requirements.txt ./requirements.txt
RUN python -m venv /opt/venv \
&& /opt/venv/bin/python -m pip install --no-cache-dir -r requirements.txt
FROM python:3.11-slim-bookworm@sha256:<digest>
WORKDIR /app
COPY --from=build /opt/venv /opt/venv
COPY app.py ./app.py
USER 10001:10001
CMD ["/opt/venv/bin/python", "app.py"]
Copy the dependency manifest before the install step and the app code after it. This lets code edits reuse the dependency layer without sending unrelated files into it. Use a lock file with specific versions for direct and transitive dependencies; where your workflow supports it, verify package hashes too. Scan the final stage because libraries copied out of the builder can still contain vulnerabilities.
If your builder needs OS packages, install only the packages it needs. Replace the package version below with an approved version available from your configured repository. Keep the package index refresh, install, and cleanup in the same layer.
RUN apt-get update \
&& apt-get install -y --no-install-recommends 'build-essential=<package-version>' \
&& rm -rf /var/lib/apt/lists/*
Use .dockerignore to keep version-control history, local caches, credentials, and keys out of the build context. Prefer explicit COPY statements over COPY . .. Keep application code readable but not writable by the runtime user. Open up only the paths the app needs to modify. Never put credentials, private keys, or tokens in the Dockerfile, including in ARG, ENV, or a shell command.
Scanning Images for Vulnerabilities
Install and Run Trivy
Trivy is an open-source scanner from Aqua Security. Download the official Linux release archive for your architecture, verify it against trusted release metadata, and save it as trivy-release.tar.gz in a fresh directory. Install the verified binary without granting the installer root access:
tar -xzf ./trivy-release.tar.gz trivy
install -d "$HOME/.local/bin"
install -m 0755 ./trivy "$HOME/.local/bin/trivy"
export PATH="$HOME/.local/bin:$PATH"
trivy --version
Start by scanning a familiar base. The mutable tag here is a scan target for practice, not a deployment pin.
trivy image python:3.11-slim
Narrow the report to high and critical findings for initial triage:
trivy image --severity HIGH,CRITICAL python:3.11-slim
Scan your repository for dependency and secret findings, and check supported configuration files for misconfigurations. Run these from a trusted project directory.
trivy fs .
trivy config .
An image scan and a configuration scan answer different questions. The image scan can identify a vulnerable package in the final filesystem. A configuration scan can flag a risky Dockerfile instruction. Neither can tell you on its own who has access to the production Docker socket.
Use Docker Scout and Hadolint
Docker Scout is Docker's own scanner. With the Scout CLI available, use quickview for an overview and cves to review individual findings. Follow your organization's rules about which images may be analyzed with connected services.
docker scout quickview python:3.11-slim
docker scout cves python:3.11-slim
Hadolint lints Dockerfiles. Run it before building to catch issues such as package-install patterns that make updates or builds harder to reproduce. It does not replace vulnerability scanning.
hadolint Dockerfile
Triage Findings and Enforce a CI Gate
For each relevant finding, identify the package, where it came from, and the vendor's fixed version. Distributions sometimes backport a fix without adopting the upstream version number you expect, so consult the distribution's advisory. If the package comes from your base, update the pinned base and rebuild. If it comes from the app, update the dependency lock to a fixed version and test the change. If there is no fix, document the exposure, compensating controls, an owner, and an expiration date for any exception.
Add this step to a GitHub Actions job after trusted setup steps install a pinned Trivy release and build the release candidate locally as app-ci:scan. It fails the job when Trivy reports a critical vulnerability. Do not set the step to continue on error.
- name: Fail on critical image vulnerabilities
run: trivy image --scanners vuln --severity CRITICAL --exit-code 1 app-ci:scan
Promote the same artifact that passed the gate. A second build after scanning may produce a different image. Record the release digest and retain scanner results so you can identify affected deployments when a new advisory arrives. A severity gate is a release decision, not proof that every lower-severity finding is acceptable.
Verify Image Provenance
A digest identifies content; a signature can help you verify who authorized that content. Docker Content Trust is the older Notary v1 signing workflow. Its availability depends on the registry and publisher, so do not assume a tag is signed or build a new policy that depends on universal Docker Content Trust support. Use a supported signing workflow, such as Sigstore Cosign or Notation, and enforce verification against an approved signer.
For example, this Cosign template verifies a pinned digest with a trusted publisher key. Replace the example registry reference and digest with your approved artifact, and obtain the public key through a trusted channel.
cosign verify --key ./publisher.pub 'example.com/team/app@sha256:<digest>'
Worked Example: Hardening a Vulnerable Flask App
Use a new directory on a disposable, patched Linux VM. The app has one route, no real credentials, and no production data. The weak version demonstrates bad packaging and runtime defaults, not an exploit. Run web requests only against 127.0.0.1. Flask's development server is suitable for this smoke test, not production.
mkdir flask-docker-lab
cd flask-docker-lab
Create app.py. The web server listens on the container's interfaces so Docker can forward traffic to it. The host-side bind in the run command is what keeps the published port on loopback.
from flask import Flask, jsonify
app = Flask(__name__)
@app.get("/")
def index():
return jsonify(status="ok")
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, debug=False, use_reloader=False)
Create requirements.txt with this example version pin. A production build should also lock transitive dependencies and use a release that passes its current security review.
Flask==3.1.2
Build and Scan the Weak Version
Save this as Dockerfile.unsafe. For this baseline only, do not create a .dockerignore yet. Make sure the directory contains just the lab files before building. The value in APP_SECRET is a dummy string the app does not use.
FROM python:latest
WORKDIR /app
COPY . .
ENV APP_SECRET=lab-placeholder-not-a-real-secret
RUN python -m pip install -r requirements.txt
CMD ["python", "app.py"]
This Dockerfile inherits the base's root user, uses a floating tag, copies the whole context, and stores a pretend secret in the image configuration. In a real repository, the same broad copy could include a developer's local credentials or version-control history.
docker build -f Dockerfile.unsafe -t flask-lab:unsafe .
trivy image --scanners vuln --severity HIGH,CRITICAL flask-lab:unsafe
Illustrative Trivy sample output only. These are mock report rows with IDs and versions omitted, not findings attributed to any Python image.
Library Vulnerability Severity Installed Version Fixed Version
[package A] [ID omitted] CRITICAL [omitted] [omitted]
[package B] [ID omitted] HIGH [omitted] [omitted]
[package C] [ID omitted] HIGH [omitted] [omitted]
[package D] [ID omitted] HIGH [omitted] [omitted]
The unsafe deployment shorthand would be docker run -p 5000:5000 flask-lab:unsafe. Do not run that form. It normally publishes on all host interfaces and applies no workload resource limits. To compare behavior in the disposable lab, use this loopback-only variant instead. It deliberately leaves the other weak defaults in place.
docker run --rm -d --name flask-unsafe -p 127.0.0.1:5000:5000 flask-lab:unsafe
If you started the baseline container, stop it before the hardened run so it releases the port.
docker stop flask-unsafe
Build the Hardened Version
Create .dockerignore before adding the dummy build token. This keeps the token file out of the ordinary context even though you will provide it separately as a BuildKit secret.
.git
.venv
__pycache__
**/__pycache__
.env
.env.*
**/.env
**/.env.*
**/*.key
**/*.pem
secrets/
**/secrets/
dbpass.txt
build-token.txt
Dockerfile.unsafe
Look up the real digest of python:3.11-slim-bookworm as shown earlier and replace both placeholders in the new Dockerfile. The secret mount is available to one build instruction. That instruction only checks that the file exists and is nonempty; it never prints or copies the token. The dependency install runs separately, without access to the mount.
# syntax=docker/dockerfile:1
FROM python:3.11-slim-bookworm@sha256:<digest> AS build
WORKDIR /build
COPY requirements.txt ./requirements.txt
RUN --mount=type=secret,id=build_token,required=true test -s /run/secrets/build_token
RUN python -m venv /opt/venv \
&& /opt/venv/bin/python -m pip install --no-cache-dir -r requirements.txt
FROM python:3.11-slim-bookworm@sha256:<digest>
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
WORKDIR /app
COPY --from=build /opt/venv /opt/venv
COPY app.py ./app.py
USER 10001:10001
EXPOSE 5000
CMD ["/opt/venv/bin/python", "app.py"]
The final stage copies only the app and its installed environment. It does not set APP_SECRET or copy the build token. The EXPOSE instruction documents the app port; it does not publish the port on the host.
(umask 077; echo 'build-token-for-lab-only' > ./build-token.txt)
docker build --secret id=build_token,src=./build-token.txt -t flask-lab:hardened .
Rescan, Run, and Verify
Use the same severity filter for the rescan so the comparison is about the images, not a change in the report settings.
trivy image --scanners vuln --severity HIGH,CRITICAL flask-lab:hardened
Illustrative Trivy sample output only. The shorter excerpt shows what a comparison might look like. It is not a measured reduction or a claim about the current base image.
Library Vulnerability Severity Installed Version Fixed Version
[package B] [ID omitted] HIGH [omitted] [omitted]
Actual results depend on the resolved images, dependencies, platform, and scanner database. Changing the base can change the report. Setting a non-root user or dropping capabilities changes what a process can do at runtime; it does not remove a vulnerable package.
Start the hardened container with no added capabilities, a read-only root filesystem, and a small writable scratch space. The limits are lab settings, not production sizing recommendations.
docker run --rm -d --name flask-hardened \
-p 127.0.0.1:5000:5000 \
--cap-drop ALL --security-opt=no-new-privileges \
--read-only --tmpfs /tmp:rw,noexec,nosuid,nodev,size=16m,mode=1777 \
--memory 256m --cpus 0.5 --pids-limit 100 \
flask-lab:hardened
Once Flask has started, verify that the route still works.
curl --fail --silent --show-error http://127.0.0.1:5000/
Illustrative response:
{"status":"ok"}
Check the configured user with docker inspect. The second command reads the effective UID of the Flask process, PID 1 inside this container. It checks the actual process identity rather than assuming the configuration tells the whole story.
docker inspect --type container --format '{{.Config.User}}' flask-hardened
docker exec flask-hardened /opt/venv/bin/python -c 'print(next(line.split()[2] for line in open("/proc/1/status") if line.startswith("Uid:")))'
Illustrative output, in command order:
10001:10001
10001
Leave the hardened container running if you want to use the inspection commands in later sections. When you are finished, stop it and remove the weak image and dummy token.
docker stop flask-hardened
docker image rm flask-lab:unsafe
rm -f ./build-token.txt
Managing Secrets Securely
Keep Credentials Out of Image History
Never put a secret in a Dockerfile ENV or ARG instruction. Image configuration, build metadata, logs, and history can expose values. A file copied into one layer remains in that layer even if you delete it in a later instruction. Deleting a password file from the final view of the filesystem does not make the image safe to share.
Run this review only on the dummy baseline image, before removing it. Do not paste history from a real image into a public issue or shared chat.
docker history --no-trunc flask-lab:unsafe
Maintain a .dockerignore and a separate Git ignore policy. The former filters the build context; it does not prevent a file from being committed. If a real secret appears in an image, build cache, or log, revoke or rotate it. Then replace affected images and review access to the registry and CI artifacts. Deleting a tag does not invalidate a credential or remove existing copies.
Use BuildKit Secrets at Build Time
Give the secret a named ID and grant access only to the trusted instruction that needs it. For this template, keep dbpass.txt out of the ordinary build context and add the matching instruction to the intended build stage.
docker build --secret id=dbpass,src=./dbpass.txt -t example-app:build .
RUN --mount=type=secret,id=dbpass,required=true test -s /run/secrets/dbpass
A secret mount does not protect a value that the build itself logs, uploads, or copies into an artifact. Do not grant secrets to untrusted Dockerfiles or build steps. Also, changing a secret's contents does not by itself invalidate a cached BuildKit instruction. If you need to test that a step reads a newly provisioned secret, rerun it without the relevant cache.
Use Runtime Secrets for Running Services
Docker Swarm secrets are granted to specific services and made available to their tasks as files. Swarm protects secret data in transit and in its manager log. In an existing disposable Linux Swarm with a sample service named lab-app already configured to read the file, an authorized administrator can grant a dummy secret like this:
docker secret create dbpass ./dbpass.txt
docker service update --secret-add source=dbpass,target=dbpass,uid=10001,gid=10001,mode=0400 lab-app
The service reads /run/secrets/dbpass. A standalone docker run container cannot consume a Swarm secret by adding that service flag. For standalone services, use a secret provider or a restricted file mount. Local Compose file-backed secrets are not the same as Swarm's managed secret store. Test that the service UID can read the file and that unrelated services cannot.
If you maintain a local environment file, restrict its on-disk permissions:
chmod 0600 ./app.env
ls -l ./app.env
Use environment files for ordinary configuration where possible. Mode 0600 protects the local file, but values passed through --env-file become container environment variables and can be visible through the Docker API. Prefer a file-based secret over an environment variable for credentials.
Runtime Hardening: Least Privilege
Set the User and Drop Capabilities
Set a numeric USER in the image and check for runtime overrides. A numeric UID does not grant file access automatically. Make files readable by the intended user and keep writes confined to designated directories. Use a matching non-root GID rather than relying on the base image's group defaults.
Start from --cap-drop ALL. Add a capability only when a documented operation requires it. For example, NET_BIND_SERVICE is a narrow exception if your workload must listen on a low port in a network namespace that enforces privileged ports. Listening on a higher port inside the container is usually simpler. Do not add broad capabilities to fix an error you have not diagnosed.
Use --security-opt=no-new-privileges to stop processes from gaining additional privileges through mechanisms such as set-user-ID executables. This does not take away privileges the container already has. Never use --privileged as an application fix: it grants all capabilities, expands access to host devices, and relaxes normal security confinement.
docker inspect --format 'user={{.Config.User}} caps_dropped={{json .HostConfig.CapDrop}} security={{json .HostConfig.SecurityOpt}}' flask-hardened
Limit Writes and Resource Use
Pair --read-only with --tmpfs for scratch paths such as /tmp. Give temporary storage a size limit, and verify it is writable by the non-root process. Send logs to standard output and standard error. If the app needs persistence, mount a dedicated volume at its data path rather than making the root filesystem writable. A read-only root filesystem does not make separately mounted volumes read-only.
Set --memory, --cpus, and --pids-limit based on observed use. The CPU setting defines a time quota, not CPU affinity. The PID limit includes threads, so test it with realistic worker counts. Verify actual enforcement on your host, especially in rootless mode, where resource controls depend on cgroup and service-manager support.
docker stats --no-stream flask-hardened
docker inspect --format 'memory={{.HostConfig.Memory}} nanocpus={{.HostConfig.NanoCpus}} pids={{.HostConfig.PidsLimit}}' flask-hardened
Keep Security Profiles Active
Docker's default seccomp profile filters system calls. Keep it on; do not use --security-opt seccomp=unconfined in production. Also keep AppArmor or SELinux active where supported. If a profile blocks a required operation, review the denial and test a narrow policy change instead of disabling the profile.
docker info --format '{{json .SecurityOptions}}'
docker inspect --format 'apparmor={{.AppArmorProfile}} selinux={{.ProcessLabel}}' flask-hardened
Interpret these fields against the host's active security module. An empty list of explicit container security overrides is not evidence that the default seccomp profile is disabled.
Securing the Docker Daemon and Host
Treat Docker Access as Administrative Access
On a conventional rootful Linux host, access to the Docker daemon is root-equivalent. A person who can control the daemon can ask it to start workloads with host-level access. Limit membership in the docker group to trusted administrators. Audit sudo rules, deployment credentials, service accounts, and CI runners too. Group membership is only one route to the API.
Never mount /var/run/docker.sock into an application, sidecar, or CI workload. A :ro bind mount does not make the API read-only. A process that can connect to the socket can still issue daemon requests. Prefer collecting the specific logs or metrics a service needs instead of handing it the socket.
ls -l /var/run/docker.sock
getent group docker
id
docker context ls
Inspect these on the intended host. Check the effective memberships of deployment accounts, including memberships managed by a directory service. A local group listing does not tell you which remote credentials reach the daemon.
Never expose the Docker API over TCP without TLS. Prefer not to open a TCP listener at all. When a remote API is necessary, require mutual TLS, restrict network reachability, and enforce authorization for client identities. Treat client keys as administrative credentials. On a Linux host, check listening sockets without making requests to the daemon's network interface.
sudo ss -ltnp
Keep Docker Engine, containerd, runc, and the host OS and kernel updated through supported channels. Schedule restarts or reboots when fixes require them. After maintenance, verify the active kernel and server-side runtime, not just the installed CLI or package files.
Choose Rootless Mode or User Namespace Remapping
Rootless mode runs the daemon and containers under an unprivileged host account. On a supported lab host, install the rootless prerequisites, including the user namespace mapping helpers and subordinate UID and GID ranges for the account. Run the setup as that regular user, not with sudo. Use a clean lab host or plan the migration from a rootful installation separately.
dockerd-rootless-setuptool.sh install
docker context use rootless
docker info --format '{{json .SecurityOptions}}'
Verify that the server reports rootless operation. A context name alone is not proof; environment overrides can direct the client elsewhere. Rootless mode limits the privileges of the daemon on the host. Someone with control of that daemon can still control that account's Docker workloads and expose data accessible to the account.
User namespace remapping is an option for a rootful daemon. It maps container IDs, including container root, to subordinate unprivileged IDs on the host. The daemon itself still runs as root, so its socket remains root-equivalent. This is a sample setting to merge into /etc/docker/daemon.json, not a replacement for the entire file.
{
"userns-remap": "default"
}
Validate the merged configuration before a planned restart. Test bind-mount ownership and account for changes to the visibility of existing images and containers when enabling remapping on an existing host.
sudo dockerd --validate --config-file=/etc/docker/daemon.json
Configuration validation does not test service restarts, file permissions, or app compatibility. Test those on a representative lab host before rolling out the change.
Docker Network Security
Separate Services by Who Needs to Talk to Them
Containers attached to the default bridge can generally reach one another unless you configure restrictions. Publishing no ports reduces host-side exposure, but does not prevent peer containers on the same network from reaching a listening service. Put related services on user-defined networks so membership is explicit and peers can resolve service names.
docker network create --driver bridge flask-lab-net
docker network inspect --format 'driver={{.Driver}} internal={{.Internal}}' flask-lab-net
Use an internal network for a tier that does not need external routing through that network. Containers on it can still communicate with one another. A service attached to another network can still have a path out through that network, so review multi-network attachments.
docker network create --internal flask-data
docker network inspect flask-data
For batch work that does not need a network at all, use --network none. The process keeps its local loopback interface but does not join a shared Docker network.
docker run --rm --network none --cap-drop ALL --security-opt=no-new-privileges flask-lab:hardened /opt/venv/bin/python -c 'print("offline job ok")'
Publish Only the Ports You Need
Use -p 127.0.0.1:5000:5000 for a local test. Do not rely on EXPOSE as an access-control setting, and avoid publishing every exposed port with -P. Avoid --network host unless there is a documented requirement: it removes a network isolation boundary rather than simply opening one port.
docker port flask-hardened 5000/tcp
Verify the bind address, not just the port number. Loopback publication is not authentication; other local processes can still connect. Keep the engine patched and review the host's effective IPv4 and IPv6 firewall policy. Docker programs networking and port-forwarding rules, so check how those rules interact with your firewall rather than assuming a generic inbound rule covers every published port. Decide which outbound connections the workload needs too, and enforce that policy at the appropriate network boundary.
Container Escape: What It Is and How to Prevent It
A container escape occurs when a process breaks out of container isolation and reaches host resources beyond the access it was meant to have. The patched runc issues CVE-2019-5736 and CVE-2024-21626 show why a working application and a clean image scan do not tell you whether the host runtime is safe. For this lab, inspect the configuration of your own patched VM. Do not recreate either issue or install an old runtime to test it.
Some options remove protections before a software vulnerability is involved:
--privileged removes multiple layers of confinement and grants broad device access.--cap-add SYS_ADMIN adds a broad capability that should not be a routine application requirement.--pid=host gives the container visibility into the host's PID namespace.--network host removes network namespace isolation. It is not a host-root grant by itself, but it exposes host networking to the workload.Inspect the actual container settings, not only its Dockerfile. Check both the original bind settings and the resolved mounts because bind mounts can be configured in more than one way.
docker inspect --type container --format 'privileged={{.HostConfig.Privileged}} cap_add={{json .HostConfig.CapAdd}} binds={{json .HostConfig.Binds}}' flask-hardened
docker inspect --type container --format 'pid={{.HostConfig.PidMode}} network={{.HostConfig.NetworkMode}} mounts={{json .Mounts}}' flask-hardened
Review replacements deployed by automation as well as manually started containers. A hardened image can be launched with unsafe flags. Investigate unexpected host paths or a socket mounted under a different filename rather than checking only for the usual socket path inside the container.
For detection, consider Falco-style runtime monitoring and host monitoring through tools such as Wazuh. Choose signals that make sense for the workload, such as unexpected process activity or changes to daemon configuration, and test how alerts reach responders. No tool proves that an escape did not happen. On a rootful systemd host, daemon logs are one starting point for reviewing a suspicious change.
sudo journalctl -u docker --since "1 hour ago" --no-pager
Treat a suspected escape as a potential host incident. Follow your isolation and evidence-preservation procedures and assess which credentials need rotation. Deleting the container alone is not an adequate response.
The CIS Docker Benchmark
The CIS Docker Benchmark is the Center for Internet Security's configuration checklist for Docker. It covers areas such as host setup, daemon configuration, images, and container runtime settings. Match the benchmark and checker to the engine and host you are assessing. A benchmark is not a vulnerability scan and does not replace a workload threat model.
Docker's docker-bench-security automates a subset of these checks. Review and pin the checker source before use. On a dedicated, authorized Linux audit VM, you can run the host script from a reviewed checkout:
sudo sh ./docker-bench-security.sh
The checker needs administrative visibility. The short-form container invocation below illustrates the access it requests. Use it only on a disposable audit VM with a reviewed local checker image already loaded under the shown tag. The --pull=never guard prevents an implicit pull of the historical image tag. Prefer the reviewed host script if the old image or its mount assumptions do not match your system.
docker run --rm --net host --pid host --cap-add audit_control \
--pull=never \
-v /etc:/etc:ro -v /var/lib:/var/lib:ro \
-v /var/run/docker.sock:/var/run/docker.sock:ro \
docker/docker-bench-security
Do not use that invocation as a production workload pattern. The mounts expose host configuration, the checker shares host namespaces, and the socket gives it daemon access despite :ro. If a check needs a host path that is missing, review the check manually rather than expanding the container's access by trial and error.
A PASS means one tested condition met the check. A WARN means a setting needs investigation; it may be a real gap or a check that does not apply to your platform. An untested control is not a pass. Start with warnings about daemon reachability and administrative access, then review image provenance and dangerous runtime flags. Fix issues in the source configuration that deploys the service so they stay fixed after redeployment.
Docker Security Cheat Sheet
Image Hardening Quick Reference
| Task | Command or setting | What to verify |
|---|---|---|
| Pin the base | FROM python:3.11-slim-bookworm@sha256:<digest> | The digest is real, approved, and appropriate for the target platform. |
| Exclude sensitive files | .dockerignore and explicit COPY | No keys, local credentials, or repository history enter the build context. |
| Separate build and runtime | COPY --from=build | Only required artifacts are copied to the final image. |
| Lint and scan | hadolint Dockerfile and trivy image --severity HIGH,CRITICAL flask-lab:hardened | The lint check covers the real Dockerfile and the scan covers the release artifact. |
| Pass build credentials | docker build --secret id=dbpass,src=./dbpass.txt . | The matching instruction mounts the file without copying or logging it. |
Runtime Flags Quick Reference
| Goal | Docker setting | What to verify |
|---|---|---|
| Run as non-root | USER 10001:10001 or --user 10001:10001 | The process uses the intended identity and has only the necessary file access. |
| Limit privileges | --cap-drop ALL --security-opt=no-new-privileges | Any capability added back has a documented reason. |
| Restrict writes | --read-only --tmpfs /tmp | Only designated directories or volumes are writable. Bound scratch space if needed. |
| Bound resource use | --memory 256m --cpus 0.5 --pids-limit 100 | Limits fit the workload and are enforced by the host. |
| Limit network exposure | -p 127.0.0.1:5000:5000 or --network none | Use loopback for local access or no network for offline work. |
| Keep confinement | Default seccomp and the supported host security module | No privileged mode or unconfined profile overrides. |
Daemon and Host Quick Reference
| Task | Command or setting | What to verify |
|---|---|---|
| Confirm patch status | docker version, docker info, and host package advisories | The active daemon, runtime, and kernel are patched. |
| Audit administrators | getent group docker and docker context ls | Only trusted people and deployment identities have daemon access. |
| Protect the API | No workload socket mounts or unauthenticated TCP listener | Remote access, if required, uses mutual TLS and restricted reachability. |
| Reduce host privileges | Rootless mode or userns-remap | Verify the active mode and test ownership and resource enforcement. |
| Check configuration drift | CIS checklist and read-only inspection of workload settings | Investigate warnings and apply fixes to the deployment source. |
Troubleshooting Docker Security Problems
Change one setting at a time in the lab. An error after hardening is evidence that the app relied on a behavior you changed. Find that dependency before you loosen a control.
| Problem | What to check | What to do |
|---|---|---|
| Trivy finds hundreds of vulnerabilities | Confirm the image reference, scanner database, and whether the findings come from OS or app packages. | Triage by severity, exposure, and available fixes. Rebuild with an approved patched base and fixed app dependencies, then rescan. |
| The image will not build after pinning | Check for an unreplaced placeholder, a copied image ID instead of a registry digest, or a platform mismatch. | Run docker buildx imagetools inspect again and verify the index or platform digest. Do not fall back to latest. |
| The container exits immediately as non-root | Look for a permission error, an inaccessible configuration file, or a startup script that assumes root. | Fix ownership or access on the exact path. Keep the app non-root and avoid making the whole tree writable. |
| A read-only filesystem breaks the app | Find where the app writes temporary files, caches, logs, or persistent data. | Send logs to standard output, use a small tmpfs for scratch data, or mount a volume at the required persistent data path. |
--cap-drop breaks the app | Identify the failed operation. A file permission or seccomp denial can look like a capability problem. | Remove the need for the operation if possible. Otherwise add only the capability you verified is necessary. |
| Rootless mode cannot bind port 80 | Distinguish the host's low-port policy from the port inside the container. | Use a higher local port, such as -p 127.0.0.1:8080:5000, or an approved host proxy when a low port is required. |
| A secret is not available at build time | Compare the CLI secret ID, Dockerfile mount ID, file path, and BuildKit setup. | Use a matching required=true mount in the correct step. Check source permissions and cache behavior without printing the value. |
| Docker Bench reports WARN everywhere | Confirm the checker can see the intended host and daemon, and that its benchmark matches the platform. | Verify key controls manually, prioritize daemon access and runtime privileges, and document genuinely inapplicable checks. |
If a lab container exits and --rm removes it before you can inspect it, rerun with the same security settings but without --rm, and name it flask-debug. Look at the exit state and application error together. An exit code alone does not prove the app ran out of memory.
docker logs --tail 50 flask-debug
docker inspect --format 'exit={{.State.ExitCode}} oom={{.State.OOMKilled}} error={{.State.Error}}' flask-debug
Review logs locally and redact sensitive values before sharing them.
Common Mistakes
:ro and assuming it is safe. Read-only filesystem permissions do not filter API requests.127.0.0.1; do not rely on the word "test" in a service name.Best Practices
Apply the Same Settings in Docker Compose
This local example is for a service that already expects a database password file. The Flask lab itself does not need a database secret. Replace the image reference with your approved digest and provision the secret file so the intended service UID can read it without granting broader access. Local Compose does not encrypt that source file.
services:
app:
image: "example.com/team/app@sha256:<digest>"
user: "10001:10001"
read_only: true
privileged: false
cap_drop:
- ALL
security_opt:
- "no-new-privileges:true"
tmpfs:
- /tmp:rw,noexec,nosuid,nodev,size=16m,mode=1777
mem_limit: 256m
cpus: 0.5
pids_limit: 100
ports:
- "127.0.0.1:5000:5000"
secrets:
- dbpass
secrets:
dbpass:
file: ./secrets/dbpass.txt
Check the Compose configuration with the same files and overrides you intend to deploy. This command checks configuration validity; it does not test that the secret is readable by the expected process or that the resource limits are enforced.
docker compose config --quiet
Is Docker Secure?
Docker can provide useful isolation for workloads you control, but its containers share a kernel. An image can be well maintained and still run insecurely if it has broad host access. A runtime can be well confined and still serve a vulnerable application. Docker security is a configuration and maintenance discipline, not a product feature you can switch on once.
If you must run arbitrary code from mutually untrusted tenants, do not rely on ordinary containers alone. Choose a stronger boundary such as separate VMs, microVMs, or purpose-built sandboxes, and design how those workloads reach secrets, networks, and management services. Keep least-privilege controls inside the stronger boundary too.
Summary
Knowledge Check
:ro not make the daemon API read-only?Answers: 1. Containers share the Docker host's kernel; VMs have separate guest kernels. 2. The digest fixes the referenced content even if the tag moves. 3. Supply the build credential through a BuildKit secret mount and the runtime credential through a service-scoped secret or restricted file. 4. The mount flag does not restrict the API requests sent through the socket. 5. Dropping capabilities removes powers the process would otherwise have, while no-new-privileges prevents gaining new privileges during execution. 6. Use -p 127.0.0.1:5000:5000. 7. Pin a patched base, rebuild, and scan the exact new release artifact you intend to deploy. 8. No. A warning identifies a condition to verify; it may be a configuration gap or an inapplicable check.
Keep Learning
Frequently Asked Questions
Continue Learning
Linux Privilege Escalation: Complete Guide from Enumeration to Root
Linux privilege escalation from enumeration to root: LinPEAS, SUID, sudo, capabilities, cron and kernel checks — with a worked lab example and cheat sheet.
Ethical Hacking · IntermediateWindows Privilege Escalation Cheat Sheet: How to Escalate Privileges in Windows
Windows privilege escalation cheat sheet: WinPEAS, unquoted service paths, AlwaysInstallElevated and Potato attacks — with a worked lab example.
Ethical Hacking · IntermediateCloud Penetration Testing: Complete Guide to AWS, Azure and GCP Security Testing
Cloud penetration testing for AWS, Azure, and GCP: the 6-phase methodology, IAM analysis, chained attack paths, and tools — with a worked lab example.
Ethical Hacking · BeginnerEthical Hacking Fundamentals: Principles, Methodology, and Best Practices
Learn the core principles of ethical hacking, the five-phase penetration testing methodology, types of security testing, and how to build your own hacking lab.
Related Security Tools
TruffleHog
TruffleHog is an open-source secrets discovery, classification, verification and analysis tool by Truffle Security. It scans Git history, GitHub, filesystems, Docker images, cloud storage and other supported sources for API keys, passwords, private keys and related machine credentials.
Wireless AttacksWifite
Learn how to use Wifite in Kali Linux with this beginner tutorial: check your WiFi adapter, install Wifite, run your first authorized WiFi audit, capture WPA handshakes and PMKIDs, and crack them with a wordlist. Includes Wifite commands, a worked example, troubleshooting for common errors, and how Wifite compares with Aircrack-ng.
Reverse EngineeringADB
ADB, or Android Debug Bridge, is a versatile command-line tool that acts as a client-server program, facilitating communication between your development machine (the client) and an Android device (running the adbd daemon) via a server process binding TCP port 5037. It ships as part of the Android SDK Platform Tools, and on Kali Linux, it's available as the `android-tools-adb` package. ADB is the standard device bridge for Android mobile pentesting and forensics, enabling actions like deploying Frida servers, pulling APKs, and capturing detailed logcat output for analysis.
Reverse EngineeringFrida
Frida is a dynamic instrumentation toolkit for developers, reverse-engineers, and security researchers. It allows you to inject snippets of JavaScript or your own library into native apps on various platforms — making it the industry standard for runtime analysis and mobile app security testing.