Skip to main content
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.

Table of Contents


Memory Limits

Docker containers run without memory constraints by default. You can view and modify these settings using docker run flags.

Default Behavior

Run a container named testone without any memory restrictions:
Inspect its memory settings:
Output:
A value of 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:
Verify:
Expected:

Unlimited Swap

By default, swap is limited to the same size as --memory. To allow unlimited swap, use --memory-swap=-1:
Inspect:
Result:
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:
Inspect:
Output:
This configuration guarantees between 100 MiB and 200 MiB of RAM, with unlimited swap.

Memory Flags Summary


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:
Assuming 2 cores, limit the container to 1 CPU:
Inspect:
You’ll see:
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:
Inspect:
Output:
This container will only run on CPU core 1.

CPU Flags Summary


Watch Video