Docker Security Cheat Sheet
Learn 14 Docker security best practices to protect containers, secure the Docker daemon, prevent privilege escalation, scan images, manage secrets, and strengthen your container supply chain.

Introduction
Docker is the most popular containerization technology. When used correctly, it can enhance security compared to running applications directly on the host system. However, certain misconfigurations can reduce security levels or introduce new vulnerabilities.
The aim of this cheat sheet is to provide a straightforward list of common security errors and best practices to assist in securing your Docker containers.
Rules
RULE #0: Keep Host and Docker Up to Date
To protect against known container escape vulnerabilities like Leaky Vessels, which typically result in the attacker gaining root access to the host, it's vital to keep both the host and Docker up to date.
This includes regularly updating:
- The host kernel.
- The Docker Engine.
Containers share the host's kernel. If the host's kernel is vulnerable, the containers are also vulnerable.
For example, the kernel privilege escalation exploit, Dirty COW, executed inside a well-insulated container would still result in root access on a vulnerable host.
Update Container Images
Updating the host and Docker is not enough on its own.
The software inside a container image (the base image, OS packages, and application dependencies) is only patched when the image is rebuilt and redeployed.
A running container is not updated in place (NIST SP 800-190 §3.1.1).
Best practices:
- Have a defined process to rebuild images regularly and redeploy the updated versions.
- Retire outdated images.
- Prune vulnerable images from registries.
- Deploy specific image versions instead of relying on mutable tags.
NIST SP 800-190 §4.2.2 recommends pruning vulnerable images from registries and deploying specific image versions, because stale images make accidental deployment of a known-vulnerable version more likely (§3.2.2).
See Rule #9 and Rule #13 for detecting vulnerabilities in images.
RULE #1: Do Not Expose the Docker Daemon Socket
The Docker socket /var/run/docker.sock is the UNIX socket that Docker listens to. This is the primary entry point for the Docker API.
The owner of this socket is root. Giving someone access to it is equivalent to giving unrestricted root access to your host.
Do Not Expose the Docker Daemon Over TCP
Do not enable a TCP Docker daemon socket.
If you are running the Docker daemon with:
-H tcp://0.0.0.0:XXX
or similar, you are exposing unencrypted and unauthenticated direct access to the Docker daemon.
If the host is internet-connected, this means the Docker daemon on your computer can be used by anyone from the public internet.
If you really have to do this, you should secure it. Check the Docker official documentation for guidance.
Do Not Expose the Docker Socket to Other Containers
Do not expose /var/run/docker.sock to other containers.
For example, avoid:
-v /var/run/docker.sock:/var/run/docker.sock
Mounting the socket read-only does not make the Docker API read-only. A process that can connect to the socket can still send requests that modify containers or the host.
Docker grants access to all daemon commands by default. Filesystem mount flags do not replace API authorization.
Equivalent Docker Compose configuration:
volumes:
- "/var/run/docker.sock:/var/run/docker.sock"
RULE #2: Set a User
Configuring the container to use an unprivileged user is the best way to prevent privilege escalation attacks.
This can be accomplished in three different ways.
Option 1: Set the User at Runtime
Use the -u option of the docker run command.
docker run -u 4000 alpine
Option 2: Set the User During Build Time
Add a user in the Dockerfile and use it.
FROM alpine
RUN groupadd -r myuser && useradd -r -g myuser myuser
# Do what you have to do as a root user,
# like installing packages.
USER myuser
Option 3: Enable User Namespace Support
Enable user namespace support in the Docker daemon:
--userns-remap=default
More information can be found in the Docker official documentation.
For additional security, you can also run Docker in rootless mode, which is discussed in Rule #11.
Kubernetes Configuration
In Kubernetes, this can be configured in the Security Context using the runAsUser field.
apiVersion: v1
kind: Pod
metadata:
name: example
spec:
containers:
- name: example
image: gcr.io/google-samples/node-hello:1.0
securityContext:
runAsUser: 4000 # Pod user ID
As a Kubernetes cluster administrator, you can configure a hardened default using the Restricted level with the built-in Pod Security admission controller.
If greater customization is desired, consider using Admission Webhooks or a third-party alternative.
RULE #3: Limit Capabilities
Grant only the specific capabilities needed by a container.
Linux kernel capabilities are a set of privileges that can be used by processes.
Docker, by default, runs with only a subset of capabilities.
You can change this and drop some capabilities using --cap-drop, or add some capabilities using --cap-add if needed.
Remember not to run containers with the --privileged flag.
This flag adds all Linux kernel capabilities to the container.
Recommended Configuration
The most secure setup is to drop all capabilities and then add only the required ones.
docker run --cap-drop all --cap-add CHOWN alpine
Kubernetes Configuration
In Kubernetes, this can be configured in the Security Context using the capabilities field.
apiVersion: v1
kind: Pod
metadata:
name: example
spec:
containers:
- name: example
image: gcr.io/google-samples/node-hello:1.0
securityContext:
capabilities:
drop:
- ALL
add: ["CHOWN"]
As a Kubernetes cluster administrator, you can configure a hardened default using the Restricted level with the built-in Pod Security admission controller.
If greater customization is desired, consider using Admission Webhooks or a third-party alternative.
RULE #4: Prevent In-Container Privilege Escalation
Always run your Docker images with:
--security-opt=no-new-privileges
This prevents privilege escalation via setuid or setgid binaries.
Kubernetes Configuration
In Kubernetes, this can be configured in the Security Context using the allowPrivilegeEscalation field.
apiVersion: v1
kind: Pod
metadata:
name: example
spec:
containers:
- name: example
image: gcr.io/google-samples/node-hello:1.0
securityContext:
allowPrivilegeEscalation: false
As a Kubernetes cluster administrator, you can configure a hardened default using the Restricted level with the built-in Pod Security admission controller.
If greater customization is desired, consider using Admission Webhooks or a third-party alternative.
RULE #5: Be Mindful of Inter-Container Connectivity
Inter-Container Connectivity (ICC) is enabled by default, allowing all containers to communicate with each other through the docker0 bridged network.
Instead of using the --icc=false flag with the Docker daemon, which completely disables inter-container communication, consider defining specific network configurations.
Recommended Practices
- Create custom Docker networks.
- Specify which containers should be attached to each network.
- Use network segmentation to control communication between containers.
This method provides more granular control over container communication.
For detailed guidance on configuring Docker networks, refer to the Docker Documentation.
Kubernetes Configuration
In Kubernetes environments, Network Policies can be used to define rules that regulate pod interactions within the cluster.
These policies provide a robust framework to control how pods communicate with each other and with other network endpoints.
Additionally, Network Policy Editor simplifies the creation and management of network policies, making it more accessible to define complex networking rules through a user-friendly interface.
RULE #5a: Be Careful When Mapping Container Ports to the Host with Firewalls Like UFW
UFW (Uncomplicated Firewall) is a popular host-based firewall for Linux.
A common misconception is that firewall rules protect all inbound traffic, including traffic destined for Docker containers.
However, Docker manages its own iptables and nftables rules directly and bypasses UFW entirely.
Other tools that use iptables or nftables can also have similar conflicts. If you are using other firewall tools, you should check whether they are working correctly.
Why This Is a Problem
When you publish a port with:
-p 8000:8000
Docker inserts iptables rules that open that port to all interfaces and all source addresses.
These rules are typically accepted before explicit firewall DENY rules are applied.
As a result, traffic may be allowed through regardless of any DENY rules you have set, which can unintentionally expose container services to the public internet.
Recommended Mitigations
Option 1: Bind Published Ports to Localhost Only
Bind the host side of the port mapping to 127.0.0.1 so the service is only reachable locally, not from external networks.
Vulnerable configuration:
docker run -p 8000:8000 myimage
Safe configuration:
docker run -p 127.0.0.1:8000:8000 myimage
Docker Compose equivalent:
services:
web:
image: myimage
ports:
- "127.0.0.1:8000:8000" # Localhost only
Option 2: Use ufw-docker or Equivalent
For UFW specifically, the ufw-docker project provides a script and supplemental iptables rules that patch Docker's networking to respect UFW policies.
This allows you to use standard UFW commands to control traffic to containers.
Install the integration rules:
sudo ufw-docker install
Allow external access to a specific container port:
sudo ufw-docker allow mycontainer 8000/tcp
Refer to the Docker and iptables documentation for a deeper explanation of how Docker interacts with the host firewall.
Docker Swarm
Option 1 does not apply to Swarm services.
A port published with docker service create --publish or docker stack deploy cannot be bound to a single host IP (moby/moby#26696).
Publishing
With the default ingress routing mesh, the published port listens on every IP address of every node in the swarm.
mode=host bypasses the routing mesh but still opens the port on all interfaces of the node that runs the task.
A service that only needs to be reached by other services should not be published.
Instead:
- Attach it to an overlay network.
- Optionally use
--internal. - Reach it by service name.
Firewall
If a service must be published, the remaining control on the node is the host firewall.
Inbound IPv4 traffic for both publishing modes is NATed.
Filter it in the DOCKER-USER chain and match the published port with conntrack's --ctorigdstport (match the original IP and ports).
This works for both modes.
Alternatively, match the incoming interface or source.
Do not rely on --dport.
In DOCKER-USER, it sees:
- The container port for
mode=host. - The published port for the ingress routing mesh.
The ingress routing mesh rewrites the port later inside the task's network namespace.
Therefore, a rule written on the wrong port matches nothing and leaves the service exposed.
IPv6
The path depends on the task's network.
If the network has no IPv6:
- The userland proxy serves a
mode=hostport on the host's IPv6 addresses. - This traffic goes through the INPUT chain.
If the network has IPv6 and ip6tables is enabled:
- Docker NATs it as well.
- It is filtered in the ip6tables
DOCKER-USERchain.
Check which path your hosts use:
ip6tables -t nat -S
Ports Between Nodes
By default, Swarm listens on the following ports:
| Port | Protocol | Purpose |
|---|---|---|
| 7946 | TCP + UDP | Node discovery |
| 4789 | UDP | Overlay network traffic (VXLAN) |
| 2377 | TCP | Cluster management on manager nodes |
Port configuration:
4789can be changed withdocker swarm init --data-path-port.2377can be changed with--listen-addr.
Allow the ports your swarm actually uses only from the other Swarm nodes.
Refer to the Docker documentation on overlay network ports and Swarm networking.
Overlay Encryption
Overlay traffic is not encrypted by default, and VXLAN has no authentication.
An open 4789/udp lets anyone who can reach it inject Ethernet frames into overlay networks (GHSA-vwm3-crmr-xfxw).
When nodes communicate over untrusted links:
- Create overlay networks with
--opt encrypted. - Allow IP protocol 50 (ESP) between the nodes.
- Never accept
4789/udpfrom untrusted sources.
The ingress network is not covered.
--opt encrypted applies only to the network it is set on.
The default ingress network used by the routing mesh stays unencrypted unless it is recreated with encryption.
Vulnerable Versions
Before Docker Engine 23.0.3 and 20.10.24, encrypted overlay networks could silently accept cleartext VXLAN packets.
This could happen, for example, when:
- The
xt_u32kernel module was missing. - A node had a single endpoint.
Relevant vulnerabilities:
- CVE-2023-28840
- CVE-2023-28842
RULE #6: Use Linux Security Modules for Runtime Security
Use seccomp, AppArmor, or SELinux for runtime security.
First of all, do not disable the default security profile.
Always start with Docker's or your host's default profile as a baseline.
Security Profile Recommendations
Seccomp
Restrict syscalls to the minimum required for your container.
Use Docker's default seccomp profile as a starting point and customize it per workload.
Reference: Docker Seccomp.
AppArmor
Apply per-container AppArmor profiles to enforce mandatory access controls.
Reference: Docker AppArmor.
SELinux
Enable SELinux on the host and ensure containers are labeled properly.
Enforce SELinux policies to prevent unauthorized access to host resources.
Reference: SELinux Guide for Docker.
Runtime Security Improvements
Behavioral Monitoring
Use tools like:
- Falco
- Tetragon
- Cilium eBPF
These tools can detect unexpected or malicious container activity.
Examples:
- Unexpected exec calls.
- Privilege escalation attempts.
- Unusual network connections.
Anomaly Detection
Continuously monitor:
- Container processes.
- Filesystem changes.
- Network activity.
Identify abnormal patterns in real time.
Kubernetes Security Context
Configure pods or containers with seccomp and AppArmor profiles in Kubernetes.
Reference: Configure a Security Context for a Pod or Container.
RULE #7: Limit Resources
Limit the following resources:
- Memory.
- CPU.
- File descriptors.
- Processes.
- Restarts.
The best way to avoid DoS attacks is by limiting resources.
Docker Configuration
You can limit:
Maximum Number of Restarts
--restart=on-failure:<number_of_restarts>
Maximum Number of File Descriptors
--ulimit nofile=<number>
Maximum Number of Processes
--ulimit nproc=<number>
You can also limit memory and CPU.
Check the documentation for more details about ulimits.
Kubernetes Configuration
You can also limit resources in Kubernetes.
References:
- Assign Memory Resources to Containers and Pods.
- Assign CPU Resources to Containers and Pods.
- Assign Extended Resources to a Container.
RULE #8: Set Filesystem and Volumes to Read-Only
Run containers with a read-only filesystem using the --read-only flag.
Docker Configuration
docker run --read-only alpine sh -c 'echo "whatever" > /tmp'
If an application inside a container has to save something temporarily, combine --read-only with --tmpfs.
docker run --read-only --tmpfs /tmp alpine sh -c 'echo "whatever" > /tmp/file'
Docker Compose Configuration
services:
alpine:
image: alpine
read_only: true
Kubernetes Configuration
In Kubernetes, this can be configured in the Security Context.
apiVersion: v1
kind: Pod
metadata:
name: example
spec:
containers:
- name: example
image: gcr.io/google-samples/node-hello:1.0
securityContext:
readOnlyRootFilesystem: true
Mount Volumes as Read-Only
If the volume is mounted only for reading, mount it as read-only.
Using -v:
docker run -v volume-name:/path/in/container:ro alpine
Using --mount:
docker run --mount source=volume-name,destination=/path/in/container,readonly alpine
RULE #9: Integrate Container Scanning Tools into Your CI/CD Pipeline
CI/CD pipelines are a crucial part of the software development lifecycle.
They should include various security checks, such as:
- Lint checks.
- Static code analysis.
- Container scanning.
Dockerfile Security Best Practices
Many issues can be prevented by following best practices when writing the Dockerfile.
Adding a security linter as a step in the build pipeline can go a long way in avoiding further headaches.
Common checks include:
- Ensure a
USERdirective is specified. - Ensure the base image version is pinned.
- Ensure OS package versions are pinned.
- Avoid using
ADDin favor ofCOPY. - Avoid curl bashing in
RUNdirectives.
References
- Docker Baselines on DevSec.
- Use the Docker command line.
- Overview of Docker Compose v2 CLI.
- Configuring Logging Drivers.
- View logs for a container or service.
- Dockerfile Security Best Practices.
Container Scanning Tools
Container scanning tools are especially important as part of a successful security strategy.
They can detect:
- Known vulnerabilities.
- Secrets.
- Misconfigurations in container images.
They provide a report of findings with recommendations on how to fix them.
Free Tools
- Clair
- Grype
- Trivy
Commercial Tools
- Snyk (open source and free option available).
- Anchore (open source and free option available).
- Docker Scout (open source and free option available).
- JFrog XRay.
- Qualys.
Tools to Detect Secrets in Images
- ggshield (open source and free option available).
- Gitleaks (open source).
- TruffleHog (open source).
Tools to Detect Misconfigurations in Kubernetes
- kubeaudit
- kubesec.io
- kube-bench
Tools to Detect Misconfigurations in Docker
- inspec.io
- dev-sec.io
- Docker Bench for Security
Tools to Detect Misconfigurations in Docker Compose Files
These tools can detect misconfigurations before deployment:
- DockSec (with
--compose). - KICS.
Continuous Vulnerability Management
A scan at build time only reflects what was known on that day.
NIST SP 800-190 recommends vulnerability management that covers the whole lifecycle of an image, from the build through the registry to runtime (§4.1.1).
Best practices:
- Rescan images in your registry and in production.
- Define a policy for which findings must be fixed.
- Define how quickly findings must be fixed.
- Rebuild and redeploy images to address vulnerabilities.
See Rule #0 for image updates.
Pinned base image versions keep builds reproducible but do not update themselves, so review and update them regularly.
RULE #10: Keep the Docker Daemon Logging Level at Info
By default, the Docker daemon is configured to have a base logging level of info.
This can be verified by checking the daemon configuration file:
/etc/docker/daemon.json
Look for the log-level key.
If the key is not present, the default logging level is info.
Additionally, if the Docker daemon is started with the --log-level option, the value of the configuration file will be overridden.
Check the Docker Daemon Logging Level
ps aux | grep '[d]ockerd.*--log-level' | awk '{for(i=1;i<=NF;i++) if ($i ~ /--log-level/) print $i}'
Why This Matters
Setting an appropriate log level configures the Docker daemon to log events that you would want to review later.
A base log level of info and above would capture all logs except the debug logs.
Until and unless required, you should not run the Docker daemon at the debug log level.
RULE #11: Run Docker in Rootless Mode
Rootless mode runs the Docker daemon and containers without host-root privileges, reducing the impact of daemon or runtime compromise.
It does not guarantee protection against host privilege escalation through kernel vulnerabilities. The shared kernel remains part of the security boundary.
Unlike rootless mode, userns-remap leaves the daemon running with root privileges.
Recommended Practices
Evaluate the specific requirements and security posture of your environment to determine if rootless mode is the best choice.
For environments where security is a paramount concern and the limitations of rootless mode do not interfere with operational requirements, it is a strongly recommended configuration.
Alternatively, consider using Podman as an alternative to Docker.
Rootless Mode Benefits
Rootless mode allows running the Docker daemon and containers as a non-root user to mitigate potential vulnerabilities in the daemon and container runtime.
Rootless mode does not require root privileges even during the installation of the Docker daemon, as long as the prerequisites are met.
Read more about rootless mode and its limitations, installation, and usage instructions on the Docker documentation page.
RULE #12: Utilize Docker Secrets for Sensitive Data Management
Docker Secrets provide a secure way to store and manage sensitive data such as:
- Passwords.
- Tokens.
- SSH keys.
Using Docker Secrets helps avoid exposing sensitive data in container images or runtime commands.
Docker Swarm Secrets
Create a secret:
docker secret create my_secret /path/to/super-secret-data.txt
Use the secret:
docker service create --name web --secret my_secret nginx:latest
Docker Compose Secrets
For local Docker Compose, file-backed secrets are bind mounts.
Protect the source files on the host with appropriate access permissions and storage encryption.
Declaring a Compose secret does not encrypt these files.
This differs from Swarm-managed secrets, which are distributed over mutual TLS and stored in an encrypted Raft log.
secrets:
my_secret:
file: ./super-secret-data.txt
services:
web:
image: nginx:latest
secrets:
- my_secret
Kubernetes Secrets
While Docker Secrets generally provide a secure way to manage sensitive data in Docker environments, this approach is not recommended for Kubernetes.
Kubernetes secrets are stored in plaintext by default.
In Kubernetes, consider additional security measures such as:
- etcd encryption.
- Third-party tools.
Refer to the Secrets Management Cheat Sheet and Kubernetes Security Cheat Sheet for more information.
Build-Time Secrets
Do not pass credentials to a build with ARG, ENV, or COPY followed by rm.
Docker warns that build arguments and environment variables persist in the final image, and a file added in one layer stays retrievable even if a later layer deletes it.
NIST SP 800-190 lists embedded clear-text secrets as an image risk (§3.1.4) and says secrets should be kept outside images (§4.1.4).
Use BuildKit Secret Mounts
Use BuildKit secret mounts instead:
RUN --mount=type=secret,id=<id>
The secret is available only during that RUN instruction.
It can be accessed:
- As a file (default
/run/secrets/<id>, or a customtarget=). - As an environment variable (
env=).
The secret is not saved in the image.
However, the command can still leak it into image files, caches, or logs.
Therefore:
- Do not write it elsewhere.
- Do not print it.
- Keep credentials out of every build stage.
- Use
.dockerignoresoCOPY . .does not pull in.envor credential files.
Multi-stage builds do not fix this on their own.
See the Node.js Docker Cheat Sheet for a worked npm example.
RULE #13: Enhance Supply Chain Security
Building on the principles in Rule #9, enhancing supply chain security involves implementing additional measures to secure the entire lifecycle of container images from creation to deployment.
Key Practices
1. Image Provenance
Document the origin and history of container images to ensure traceability and integrity.
2. SBOM Generation
Create a Software Bill of Materials (SBOM) for each image.
An SBOM details all components, libraries, and dependencies for transparency and vulnerability management.
3. Image Signing
Digitally sign images to verify their integrity and authenticity, establishing trust in their security.
4. Trusted Registry
Store documented and signed images with their SBOMs in a secure registry that:
- Enforces strict access controls.
- Supports metadata management.
5. Secure Deployment
Implement secure deployment policies, such as:
- Image validation.
- Runtime security.
- Continuous monitoring.
These help ensure the security of deployed images.
6. Continuous Vulnerability Management
Match the SBOM of each deployed image against newly disclosed vulnerabilities.
Rebuild and redeploy patched images.
See the Vulnerable Dependency Management Cheat Sheet.
Podman as an Alternative to Docker
Podman is an OCI-compliant, open-source container management tool developed by Red Hat.
It provides a Docker-compatible command-line interface and a desktop application for managing containers.
It is designed to be a more secure and lightweight alternative to Docker, especially for environments where secure defaults are preferred.
Security Benefits of Podman
1. Daemonless Architecture
Unlike Docker, which requires a central daemon (dockerd) to create, run, and manage containers, Podman directly employs the fork-exec model.
When a user requests to start a container:
- Podman forks from the current process.
- The child process execs into the container runtime.
2. Rootless Containers
The fork-exec model facilitates Podman's ability to run containers without requiring root privileges.
When a non-root user initiates a container start, Podman forks and execs under the user's permissions.
3. SELinux Integration
Podman is built to work with SELinux.
SELinux provides an additional layer of security by enforcing mandatory access controls on containers and their interactions with the host system.
References
- Docker Engine Security
- Docker Build Attestations
- Docker Build Secrets
- NIST SP 800-190: Application Container Security Guide
About the author
- cto saleslyt.com academy.saleslyt.com
Comments
Join the discussionNo comments yet. Be the first to comment.





