Last active
May 9, 2024 16:03
-
-
Save stefanpejcic/be8eded2840c41b4318963c20e58d332 to your computer and use it in GitHub Desktop.
Limit total RAM & CPU usage of all docker containers combined
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# https://unix.stackexchange.com/questions/537645/how-to-limit-docker-total-resources | |
# https://www.freedesktop.org/wiki/Software/systemd/ControlGroupInterface/ | |
CPU_PERCENTAGE="90" | |
RAM_PERCENTAGE="90" | |
# Get total RAM in bytes | |
total_ram=$(grep MemTotal /proc/meminfo | awk '{print $2}') | |
# Calculate % of RAM | |
memory_limit=$(echo "scale=2; $total_ram * $RAM_PERCENTAGE / 100 / 1024 / 1024" | bc) # Convert to GB | |
# Create the systemd slice file | |
cat <<EOF | sudo tee /etc/systemd/system/docker_limit.slice | |
[Unit] | |
Description=Slice that limits docker resources | |
Before=slices.target | |
[Slice] | |
CPUAccounting=true | |
CPUQuota=${CPU_PERCENTAGE}% | |
MemoryAccounting=true | |
MemoryLimit=${memory_limit}G | |
EOF | |
# create the docker daemon configuration file | |
cat <<EOF | sudo tee /etc/docker/daemon.json | |
{ | |
"storage-driver": "devicemapper", | |
"cgroup-parent": "docker_limit.slice" | |
} | |
EOF | |
# reload systemd daemon | |
sudo systemctl daemon-reload | |
# start the docker_limit slice | |
sudo systemctl start docker_limit.slice | |
# restart docker | |
systemctl restart docker | |
# verify it works with | |
# | |
# systemd-cgtop |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment