G
GuideDevOps
Lesson 10 of 13

Resource Limits & Monitoring

Part of the Docker tutorial series.

In a production environment, one misbehaving container could consume all host resources, crashing other services. Docker allows you to set strict limits on CPU and Memory.

1. Setting Resource Limits

Memory Limits

You can set a hard limit (--memory) and a soft limit (--memory-reservation).

Action:

# Start a container with a 512MB limit
docker run -d --name limited-nginx --memory="512m" nginx

Result:

f5e6d7c8b9a0...

CPU Limits

You can specify how many "shares" or a percentage of a CPU a container can use.

Action:

# Limit the container to 0.5 (50%) of one CPU core
docker run -d --name cpu-limited --cpus="0.5" nginx

Result:

a1b2c3d4e5f6...

2. Monitoring Container Performance

Docker provides built-in tools to see how your containers are behaving in real-time.

Live Statistics

Action:

docker stats --no-stream

Result:

CONTAINER ID   NAME             CPU %     MEM USAGE / LIMIT     MEM %     NET I/O          BLOCK I/O   PIDS
f5e6d7c8b9a0   limited-nginx    0.00%     2.34MiB / 512MiB      0.46%     1.02kB / 0B      0B / 0B     2
a1b2c3d4e5f6   cpu-limited      0.00%     2.31MiB / 15.63GiB    0.01%     1.02kB / 0B      0B / 0B     2

3. Handling Crashes (Restart Policies)

Docker can automatically restart your container if it crashes or the host reboots.

PolicyDescription
noDo not restart (Default).
on-failureRestart only if the container exits with a non-zero code.
alwaysAlways restart, regardless of the exit code.
unless-stoppedSimilar to always, but doesn't restart on host boot if it was manually stopped.

Action:

docker run -d --name auto-restart --restart unless-stopped nginx

Summary

  • Always set limits in production to prevent "noisy neighbors."
  • Use docker stats to monitor real-time resource usage.
  • Use Restart Policies to keep your applications highly available.