Docker interview question · Most asked
How do you limit a container's CPU and memory, and what happens when it exceeds them?
Summary
Use --memory (and optionally --memory-swap) and --cpus (or CPU shares) with docker run, or deploy.resources.limits in Compose. When a container exceeds its memory limit, the kernel's OOM killer kills a process inside it (the container usually exits with code 137); exceeding the CPU limit causes throttling, not killing.
Longer Answer
Runtimes inside containers must respect the limits: modern JVMs (container-aware since Java 10, backported to 8u191), Node.js and Go read cgroup limits, but explicit tuning (-XX:MaxRAMPercentage, --max-old-space-size) is still common. Without limits, one container can starve everything else on the host. docker stats shows live usage.
Key Points
- --memory and --cpus.
- Memory over limit: OOM kill (137).
- CPU over limit: throttling.
- Make runtimes respect cgroup limits.
More most-asked Docker questions
- What is the difference between an image and a container, and how do image layers work?
- What is a container, and how does it differ from a virtual machine?
- What are multi-stage builds, and why use them?
- CMD or ENTRYPOINT: what is the difference, and what are exec and shell forms?
- How does Docker build caching work, and how do you order a Dockerfile to use it well?
- What are Dockerfile best practices for production images?
- ARG or ENV: what is the difference, and how do you pass secrets into a build safely?
- How do you secure Docker containers and images?