SyntaxStudy
Sign Up
Docker Resource Limits and Container Security
Docker Beginner 1 min read

Resource Limits and Container Security

By default, a container can consume all available CPU and memory on the host, which can starve other containers or the host OS. The --memory flag caps RAM usage; Docker sends SIGKILL to the container if it exceeds the limit. --cpus limits the container to a fraction of a CPU core. For I/O, --device-read-bps and --device-write-bps throttle disk throughput. Security hardening starts with running as a non-root user inside the container. The Dockerfile should create a dedicated user with RUN adduser and switch to it with USER. --read-only mounts the container filesystem as read-only, forcing all writes to explicit tmpfs mounts or volumes. --cap-drop ALL --cap-add NET_BIND_SERVICE removes all Linux capabilities except those explicitly needed. Never pass secrets via environment variables if avoidable — they appear in docker inspect output. Docker secrets (in Swarm mode) or Kubernetes secrets mounted as files are more secure. Regularly scan images for vulnerabilities with docker scout cves or Trivy to catch known CVEs in base images and dependencies.
Example
# Resource-limited, security-hardened container
docker run -d \
  --name api \
  --memory 256m \
  --memory-swap 256m \
  --cpus 0.5 \
  --read-only \
  --tmpfs /tmp:size=64m \
  --cap-drop ALL \
  --cap-add NET_BIND_SERVICE \
  --security-opt no-new-privileges \
  --user 1001:1001 \
  -p 3000:3000 \
  myapp:2.1.0

# Check applied limits
docker inspect api --format '{{.HostConfig.Memory}}'
docker inspect api --format '{{.HostConfig.NanoCpus}}'

# Verify read-only filesystem
docker inspect api --format '{{.HostConfig.ReadonlyRootfs}}'

# Scan image for CVEs
docker scout cves myapp:2.1.0

# Check if image runs as root (empty = root = bad)
docker inspect myapp:2.1.0 --format '{{.Config.User}}'

# trivy scan (open-source alternative)
# trivy image myapp:2.1.0