Memory limit test in a Bash container
Go to Project 8 from the git repository root:
cd projects/p08
Project structure:
.
└── docker-compose.yml
Files
docker-compose.yml
services:
test:
image: bash:5.2
environment:
- ALLOCATE
command:
- -c
- 'fallocate -l $ALLOCATE /app/test && echo $(( $(stat /app/test -c "%s") / 1024 / 1024))'
deploy:
resources:
limits:
memory: 50MB
mem_swappiness: 0
tmpfs:
- /app
Description
This example shows the memory testing in a bash container, where the “fallocate” command generates a file with a defined size stored in memory using tmpfs. We use an environment variable to set the allocated memory and the memory limit is defined in the compose file as 50 MiB.
Start the test
The container will have 50MB memory limit. (It must be at least 6MB in Docker Compose 1.27.4). The examples below will test the memory usage from 10MB to 50MB increased by 10MB for each test.
ALLOCATE=10MiB docker compose run --rm test
ALLOCATE=20MiB docker compose run --rm test
ALLOCATE=30MiB docker compose run --rm test
ALLOCATE=40MiB docker compose run --rm test
ALLOCATE=50MiB docker compose run --rm test
Running it in Docker Desktop on macOS I get the following output:
fallocate: fallocate '/app/test': Out of memory
Out of memory
Running it on a virtual machine with an Ubuntu 20.04 host the output is:
Out of memory
Since there is some additional memory usage in the container, it kills the process at 50MiB even though 50 is still allowed.
Explanation of the parameters
The “docker compose run” is similar to “docker run”, but it runs a service from the compose file. “–rm” means the same as it meant for “docker run”. Deletes the container right after it stopped.
Clean the project:
docker compose down
The containers were deleted automatically, but it can still delete the network.