How to Configure WSL 2 Memory Limits and Swap Files in Windows 11 Using PowerShell

By default, Windows Subsystem for Linux (WSL 2) dynamically allocates up to 50% of your total host RAM (or up to 8GB on machines with less than 16GB) to the underlying Linux virtual machine. When compiling large software repositories, executing high-concurrency Docker containers, or training local machine learning models, WSL can consume all assigned host memory, causing Windows desktop applications to stutter. Authoring a tailored .wslconfig file via PowerShell allows you to cap Linux RAM usage and establish dedicated swap files.

Understanding WSL 2 Memory Configuration Parameters

The global .wslconfig configuration file governs hypervisor resource allocation:

  • memory=<size>: Establishes a hard ceiling on physical RAM assigned to the WSL 2 utility virtual machine (e.g. memory=6GB).
  • swap=<size>: Sets the capacity of the Linux virtual swap space on the Windows host disk (e.g. swap=8GB). Setting swap=0 disables swap entirely.
  • swapFile=<path>: Redirects the swap file to a high-speed secondary NVMe drive (e.g. D:\WSLSwap\swap.vhdx) to protect your primary system drive from wear.
  • autoMemoryReclaim=gradual: Automatically releases idle memory allocated to Linux back to the Windows host operating system in the background.

Configuring Resource Limits in .wslconfig via PowerShell

To cap WSL memory allocation and configure a high-speed swap file using PowerShell:

# Define global WSL configuration path
$wslConfigPath = "$HOME\.wslconfig"

# Construct resource-tuning configuration payload
$configContent = @"
[wsl2]
memory=8GB
swap=8GB
swapFile=C:\WSL\swap.vhdx
localhostForwarding=true

[experimental]
autoMemoryReclaim=gradual
sparseVhd=true
"@

# Create target directory for swap file if absent
if (-not (Test-Path "C:\WSL")) {
    New-Item -ItemType Directory -Path "C:\WSL" -Force | Out-Null
}

# Write configuration file with UTF8 encoding
Set-Content -Path $wslConfigPath -Value $configContent -Encoding UTF8
Write-Host "WSL 2 memory and swap configuration deployed to $wslConfigPath" -ForegroundColor Green

This automated script caps Linux RAM consumption at 8GB, configures an 8GB dedicated swap space, and activates gradual background memory reclamation.

Applying Configuration Changes and Verifying Memory

To enforce newly defined memory limits:

  1. Open an elevated PowerShell prompt and terminate the WSL hypervisor:
    wsl --shutdown
  2. Relaunch your Linux distribution:
    wsl
  3. Inspect active memory allocations inside Linux:
    free -h
  4. Confirm that Mem Total reflects your exact 8Gi ceiling and Swap Total reflects your 8Gi allocation.

Configuring granular memory bounds for WSL 2 preserves host system responsiveness while providing predictable performance for developer workloads.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.