By default, Docker containers can use as much CPU and RAM as the host has.
That sounds flexible, but it’s dangerous.
Imagine one buggy app:
That’s why Docker gives resource control.
Two important terms:
๐ Reservation = “at least this much”
๐ Limit = “never more than this”
--cpus="0.5" → half of one CPU core--cpu-shares → priority weight (default 1024)--cpu-period + --cpu-quota → advanced tuningExample meaning:
100m = 0.1 CPU (10%)500m = 0.5 CPU1000m = 1 full CPU256m = 256 MB1g = 1 GB๐ Golden rule:
Never allocate 100% of host resources.
Always keep 20–30% for OS + Docker daemon.
docker run -d --name web1 \ --memory-reservation=256m \ --memory=512m httpd
docker run -d --name web1 \
--memory-reservation=256m \
--memory=512m httpdMeaning:
docker run -d --name web2 --cpus="0.5" httpd
docker run -d --name web2 --cpus="0.5" httpdMeaning:
docker run -d --name web3 --cpu-shares=512 httpd
docker run -d --name web3 --cpu-shares=512 httpdMeaning:
Good for:
docker run -d --cpu-period=100000 --cpu-quota=50000 httpd
docker run -d --cpu-period=100000 --cpu-quota=50000 httpdCalculation:
Used when you need precise tuning.
docker run -d --memory=512m --memory-swap=512m httpd
docker run -d --memory=512m --memory-swap=512m httpdMeaning:
docker stats
docker statsShows:
docker inspect web1
docker inspect web1Look for:
top htop free -m
top
htop
free -m๐ Always monitor both Docker + host.
Host:
Reserve 30% for OS:
Run 4 containers:
--cpus=0.5 each → 2 CPUs--memory=1g each → 4 GBResult:
Even with limits, containers can still be dangerous if hacked.
A bad container can:
Security = layered protection, not one command.
Smaller image = fewer vulnerabilities.
FROM alpine:3.18
FROM alpine:3.18RUN adduser -D appuser USER appuser
RUN adduser -D appuser
USER appuserIf container is hacked → attacker gets limited user, not root.
Old images = known CVEs.
Rebuild regularly:
docker pull nginx docker build --no-cache .
docker pull nginx
docker build --no-cache .Builder has tools.
Final image has only the app.
Smaller + safer.
docker run --cap-drop=ALL nginx
docker run --cap-drop=ALL nginxRemoves unnecessary privileges.
docker run --security-opt=no-new-privileges nginx
docker run --security-opt=no-new-privileges nginxEven if exploited → cannot gain extra rights.
docker run -d --memory=512m --cpus="0.5" nginx
docker run -d --memory=512m --cpus="0.5" nginxStops runaway attacks.
--network host unless requiredNever store passwords in ENV.
Use secrets instead.
Scan before deploy:
Avoid:
docker run -d --name safe-app \ --memory=512m --cpus="0.5" \ --security-opt=no-new-privileges \ --cap-drop=ALL \ --read-only \ --tmpfs /tmp:rw,size=64m \ myuser/app:1.0
docker run -d --name safe-app \
--memory=512m --cpus="0.5" \
--security-opt=no-new-privileges \
--cap-drop=ALL \
--read-only \
--tmpfs /tmp:rw,size=64m \
myuser/app:1.0What this gives you: