CPU limit test
Go to Project 9 from the git repository root:
cd projects/p09
Project structure:
.
└── Dockerfile
Files
Dockerfile
# Based on "Petar Maric outdated image"
# https://github.com/petarmaric/docker.cpu_stress_test
FROM ubuntu:20.04
# Update the Ubuntu package index and install the required Ubuntu packages
RUN apt-get update \
&& apt-get install -y --no-install-recommends stress
# Parameterize this Dockerfile, by storing the app configuration within environment variables
ENV STRESS_TIMEOUT 120
ENV STRESS_MAX_CPU_CORES 1
CMD stress --cpu $STRESS_MAX_CPU_CORES --timeout $STRESS_TIMEOUT
We test the CPU limit in this example using an image based on petermaric/docker.cpu-stress-test. Since that image is outdated, we create a new image similar to Peter Maric’s work.
docker build -t localhost/stress .
Execute the following command to test a whole CPU core:
docker run -it --rm \
-e STRESS_MAX_CPU_CORES=1 \
-e STRESS_TIMEOUT=30 \
--cpus=1 \
localhost/stress
Run “top” in an other terminal to see that the “stress” process uses 100% of one CPU. To see the same result on any host operating system, we will run top in an Ubuntu container using the process namespace of the host.
docker run --rm -it --pid host ubuntu:20.04 top
Press Ctrl-C and execute the following command to test two CPU core and allow the container to use only 1 and a half CPU.
docker run -it --rm \
-e STRESS_MAX_CPU_CORES=2 \
-e STRESS_TIMEOUT=30 \
--cpus=1.5 \
localhost/stress
Use “top” again to see that the “stress” process uses 75% of two CPU.
You can test on one CPU core again and allow the container to use 50% of a specific CPU core by setting the core index.
docker run -it --rm \
-e STRESS_MAX_CPU_CORES=1 \
-e STRESS_TIMEOUT=60 \
--cpus=0.5 \
--cpuset-cpus=0 \
localhost/stress
You can use top again, but do not forget to add the index column to the list:
run
docker run --rm -it --pid host ubuntu:20.04 top
press “f”
Select column “P” by navigating with the arrow keys
Press “SPACE” to select “P”
Press “ESC”
Now you can see the indexes in the column “P”.
Press “1” to list all the CPU-s at the top of the terminal so you can see the usage of all the CPU-s.