Running Docker on a Budget Machine
Learn some tips for running Docker containers on a budget machine. We will learn how to limit CPU usage, memory usage, and other resources that Docker containers can consume.
Table of Contents 📖
Docker and Budget Machines
Docker containers are lightweight compared to traditional virtual machines, as they share the host system's kernel. However, running Docker on a machine with limited resources should be configured carefully to avoid performance issues. By optimizing how resources are allocated and ensuring that containers don't consume excessive CPU, memory, or disk space, you can achieve efficient containerization even on limited hardware.
WARNING: Docker containers can still consume significant CPU and memory depending on the applications they run.
Limiting CPU Usage
By default, Docker containers have access to all available CPU resources on the host machine. We can limit the number of CPUs a container can use or even set a CPU quota on containers.
docker run --cpus="1.0" my_container
By setting --cpus="1.0", you're telling Docker that the container should be allowed to use up to 1 full CPU core worth of processing power. If the container tries to use more than this, the system will throttle its CPU usage to stay within the limit.
INFO: Fractional CPUs are also supported. For example, --cpus="0.5" would limit the container to using half of a CPU core.
docker run --cpu-shares=512 my_container
The --cpu-shares flag sets the CPU weight/shares for the container. The value 512 specifies how much CPU time the container is allocated relative to other containers running on the same host. 1024 is the default value for CPU shares. A container with higher CPU shares gets more CPU time when the host is under heavy load.
INFO: There are a few more flags than these which are listed in the official Docker documentation.
Limiting Memory Usage
docker run --memory="512m" my_container
The --memory flag sets a memory limit for the container. In this case, the container is limited to 512 megabytes of RAM.
docker run --memory="512m" --memory-swap="1g" my_container
The --memory-swap flag sets the total memory limit (RAM + swap) to 1 GB. It defines the combined amount of physical memory and swap space the container can use. Here, this is 512 MB of RAM and 512 MB of swap space.
INFO: Swap memory is a portion of the hard drive that acts as an extension of a computer's physical RAM. When the system's RAM becomes full and there are no more available memory resources for running applications, the operating system moves some of the inactive data from RAM to the swap space on the disk to free up memory for other tasks.