In this lesson, you’ll learn how to manage memory and CPU usage in Docker containers. Proper resource constraints help ensure predictable performance and protect the host from runaway containers.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
Table of Contents
Memory Limits
Docker containers run without memory constraints by default. You can view and modify these settings usingdocker run flags.
Default Behavior
Run a container named testone without any memory restrictions:0 indicates “no limit.”
Hard Memory Limit
Set a hard cap on RAM usage with--memory. The following command limits the container to 200 MiB:
Unlimited Swap
By default, swap is limited to the same size as--memory. To allow unlimited swap, use --memory-swap=-1:
Unlimited swap (
MemorySwap: -1) can lead to performance degradation if the host starts swapping heavily. Monitor your containers closely when using this option.Soft Memory Reservation
With--memory-reservation, you set a soft limit that Docker tries to enforce under memory contention:
Memory Flags Summary
| Flag | Description | Example |
|---|---|---|
| —memory | Hard limit for container memory | --memory=200m |
| —memory-reservation | Soft (guaranteed) memory reservation | --memory-reservation=100m |
| —memory-swap | Total memory + swap limit (-1 = unlimited) | --memory-swap=-1 |
| —memory-swappiness | Tendency to swap (0–100) | --memory-swappiness=10 |
CPU Limits
Docker lets you restrict CPU usage by setting the number of CPUs or pinning containers to specific cores.Limiting CPU Count
First, check your host’s CPU count:NanoCpus: 1000000000 represents 1 full CPU core.
Pinning to Specific Cores
Use--cpuset-cpus to bind a container to specific cores. For example, pin to core 1:
CPU Flags Summary
| Flag | Description | Example |
|---|---|---|
| —cpus | Number of CPU cores (fractional OK) | --cpus=1.5 |
| —cpuset-cpus | Bind container to specific cores | --cpuset-cpus="0,1" |