This lab covers resource isolation using Linux Cgroups in Docker containers.
You will learn how to limit CPU, memory, and other resources for containers to prevent resource contention and ensure fair sharing.
By the end of this lab, you will understand how to use Docker commands to enforce resource constraints.
CPU Limits
Use --cpus to limit CPU usage as a fraction of available cores.
# Limit container to 0.5 CPU coresdockerrun-d--cpus=0.5--namecpu-limitednginx
# Check resource usagedockerstatscpu-limited
# Clean updockerstopcpu-limited
dockerrmcpu-limited
Memory Limits
Use --memory to set a hard memory limit.
# Limit container to 128MB RAMdockerrun-d--memory=128m--namemem-limitednginx
# Check resource usagedockerstatsmem-limited
# Test memory limit by running a memory-intensive processdockerrun--memory=50mstress--vm1--vm-bytes100m
# Clean updockerstopmem-limited
dockerrmmem-limited
CPU Sets
Use --cpuset-cpus to pin container to specific CPU cores.
# Pin container to CPU cores 0 and 1dockerrun-d--cpuset-cpus=0,1--namecpu-pinnednginx
# Check which CPUs the container is usingdockerexeccpu-pinnedcat/proc/self/status|grepCpus_allowed
# Clean updockerstopcpu-pinned
dockerrmcpu-pinned
Combined Resource Limits
Combine multiple resource constraints for comprehensive control.
# Limit both CPU and memorydockerrun-d--cpus=1.0--memory=256m--namecombined-limitsnginx
# Check all resource limitsdockerinspectcombined-limits|grep-A10"HostConfig"# Clean updockerstopcombined-limits
dockerrmcombined-limits
Monitoring Resource Usage
Use docker stats to monitor container resource usage in real-time.
# Start multiple containers with different limitsdockerrun-d--cpus=0.5--memory=128m--namecontainer1nginx
dockerrun-d--cpus=1.0--memory=256m--namecontainer2nginx
# Monitor resource usagedockerstats
# Clean updockerstopcontainer1container2
dockerrmcontainer1container2