WSL2 Tips: Limit CPU/Memory When using Docker

Ali Bahraminezhad
ITNEXT
Published in
2 min readOct 1, 2020

--

The Windows Subsystem for Linux (WSL) is an ultimate feature from Microsoft that enables developers to run a GNU/Linux environment directly on Windows, unmodified, without the overhead of a traditional virtual machine or the dual-boot setup.

In WSL2, they made lots of performance improvement alongside adding new features such as Managed VM, Full Linux Kernel and Full system call compatibility.

If you enable and install WSL-2 on your Windows, in Docker-desktop can use WSL-2 based engine for better performance.

Docker Desktop uses the dynamic memory allocation feature in WSL 2 to greatly improve the resource consumption. This means, Docker Desktop only uses the required amount of CPU and memory resources it needs, while enabling CPU and memory-intensive tasks such as building a container to run much faster.

https://docs.docker.com/docker-for-windows/wsl/

Dynamic memory allocation and more CPU power! Looks great! But take a look at the following image:

Insane memory consumption : Docker on WSL2

Docker on WSL-2 might allocate all available memory, and it eventually causes memory starvation for OS and other applications.

Memory/CPU limit settings

On the legacy Hyper-V backend engine, memory and CPU allocation were easy to manage, that’s also possible in WSL-2 but a bit more tricky!

In my scenario, I prefer to allocate only four CPU Cores and Max three GB of memory.

Open Windows Terminal/CMD/PowerShell and run the commands below:

# turn off all wsl instances such as docker-desktop
wsl --shutdown
notepad "$env:USERPROFILE/.wslconfig"

Edit .wslconfig file with notepad and write down these settings:

[wsl2]
memory=3GB # Limits VM memory in WSL 2 up to 3GB
processors=4 # Makes the WSL 2 VM use two virtual processors

Save the file and restart the docker-desktop service!

Memory allocation cap to 3GB! 🤘

Conclusion

WSL-2 setting isn’t just limited to CPU and Memory; there are more other settings you can apply. Read more about it here.

--

--

I’m a geek, a software engineer who likes to build amazing stuff 😉Here on Medium I write about different things but mostly focused on programming and .NET!