Docker & Containers (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)
How do you limit CPU, memory, and swap resources for a Docker container?
senior LevelMost AskedCode ExampleDocker & ContainersSystem Design
In Simple Words: Without resource constraints, a single runaway memory leak or infinite loop in a container can starve the host OS and trigger the Linux kernel Out-Of-Memory (OOM) killer against critical host daemons.
bash
docker run -d \
--name payment-service \
--memory="512m" \
--memory-reservation="256m" \
--memory-swap="1g" \
--cpus="1.5" \
--pids-limit=100 \
my-app:v1
--memory="512m": Hard memory limit. If the container exceeds 512MB, the Linux kernel OOM killer sendsSIGKILLto the process (Exit code 137).--memory-reservation="256m": Soft memory limit activated only when the host experiences memory pressure.--cpus="1.5": Guarantees the container at most 150% of a single CPU core (1.5 cores) using CFS bandwidth quotas.--pids-limit=100: Protects against fork bombs from exhausting host process IDs.