Linux & OS Intermediate

Optimizing WSL2 Ubuntu Swap Configuration for Enhanced Performance

Resolve low performance in WSL2 Ubuntu due to insufficient swap memory. Learn to configure global WSL2 settings and dedicated swap files for better system responsiveness.

👨‍💻
Senior Systems Architect • Verified in Staging Labs

Resolve low performance in WSL2 Ubuntu due to insufficient swap memory. Learn to configure global WSL2 settings and dedicated swap files for better system responsiveness.

Introduction

Running Linux workloads efficiently on Windows Subsystem for Linux 2 (WSL2) is crucial for many developers and system administrators. However, it's a common experience for users to encounter performance bottlenecks, slow application response times, or even Out Of Memory (OOM) errors within their WSL2 Ubuntu environment. A primary culprit behind these issues is often the default or misconfigured swap memory allocation. This guide will walk you through diagnosing, understanding, and robustly resolving low swap memory configurations in WSL2 Ubuntu to significantly boost your system's performance and stability.

Symptom & Error Signature

Users typically experience a range of symptoms indicating insufficient swap memory within WSL2:

  • Slow or unresponsive applications: Especially under load, applications like web servers (Nginx, Apache), databases (MySQL, PostgreSQL), or Docker containers become sluggish.
  • System freezes or crashes: The WSL2 instance might become unresponsive, requiring a full restart of the subsystem.
  • Out Of Memory (OOM) Killer invocations: The Linux kernel's OOM killer might terminate critical processes to free up memory, leading to unexpected application shutdowns.
  • High CPU usage without apparent reason: The system spends more time moving data in and out of RAM due to memory pressure, leading to "thrashing."

You might observe these symptoms through various command outputs:

# Check overall memory and swap usage
free -h

# Example output indicating low or no swap
              total        used        free      shared  buff/cache   available
Mem:           15Gi       8.0Gi       5.0Gi       1.0Gi       2.0Gi       6.0Gi
Swap:            0B          0B          0B

# Check for OOM killer messages in the kernel logs
dmesg | grep -i 'oom-killer|out of memory'

# Example OOM killer message
[ 1234.567890] Out of memory: Killed process 1234 (nginx) total-vm:456789kB, anon-rss:345678kB, file-rss:12345kB, shmem-rss:0kB

# Inspect swap status
swapon --show

# Example output showing no active swap
# (No output means no swap is active)

Root Cause Analysis

WSL2 operates as a lightweight virtual machine, and its resource management differs from a traditional bare-metal Linux installation. The core reasons for low swap-related performance issues in WSL2 Ubuntu are:

  1. Default Resource Allocation: By default, WSL2 dynamically allocates memory up to a certain percentage of your Windows host's total RAM (typically 50% for memory and 25% for swap, if not specified) or a hard cap if you have limited RAM. While dynamic, this default swap configuration is often insufficient for demanding applications or development environments, particularly if the Windows host itself is under memory pressure.
  2. wsl .wslconfig Oversight: Many users are unaware that WSL2's global resource limits, including the total swap space available to all WSL2 distributions, can and should be configured via a special file named .wslconfig in their Windows user profile directory (%UserProfile%). If this file is missing or misconfigured, WSL2 uses default, potentially inadequate, settings.
  3. No Explicit In-Distro Swap: Unlike traditional Linux installations that often include a dedicated swap partition or a large swap file, WSL2 Ubuntu distributions might not have an explicitly configured swap file within the Linux filesystem by default. While the .wslconfig parameter for swap does create a virtual swap disk for the WSL2 VM, some applications or specific kernel behaviors might benefit from or require a dedicated swap file managed directly by the Linux OS.
  4. Swappiness Setting: The swappiness kernel parameter dictates how aggressively the Linux kernel uses swap space. A high swappiness value (default is 60) can cause the system to swap out active memory pages too readily, even if there's available physical RAM, leading to performance degradation. Conversely, a very low value might prevent the system from using swap when truly necessary, leading to OOM issues.

Step-by-Step Resolution

Follow these steps to correctly configure swap memory in your WSL2 Ubuntu environment and mitigate performance issues.

1. Assess Current WSL2 & Ubuntu Memory/Swap Usage

Before making changes, understand your current memory landscape.

  1. Open your WSL2 Ubuntu terminal.
  2. Check memory and swap usage:
    free -h
    
    Pay close attention to the Swap row. If it shows 0B or a very small value, your system is likely suffering from insufficient swap.
  3. Check active swap devices:
    swapon --show
    
    This command lists any active swap files or partitions. If it returns no output, no explicit swap is configured within your Ubuntu distribution.
  4. Check the current swappiness value:
    cat /proc/sys/vm/swappiness
    
    The default is usually 60.

2. Configure WSL2 Global Resource Limits via .wslconfig

This is the most critical step as it sets the overall resource boundaries for all your WSL2 distributions.

  1. Locate or Create .wslconfig: On your Windows host, open File Explorer and navigate to your user profile directory, typically C:Users<YourUsername>. If a file named .wslconfig exists, open it with a text editor (e.g., Notepad, VS Code). If it doesn't exist, create a new file named .wslconfig (ensure it has no file extension).

    The file name MUST be .wslconfig, not .wslconfig.txt or similar. Ensure file extensions are visible in Windows Explorer if you're having trouble.

  2. Edit .wslconfig: Add or modify the following content in your .wslconfig file. Adjust memory, processors, and swap values based on your host machine's resources and your workload requirements.

    [wsl2]
    # Limits the amount of memory that the WSL 2 VM can use.
    # Replace <YourRAMValue> with a value suitable for your system (e.g., 8GB, 12GB).
    # This should be less than your total Windows RAM to prevent host instability.
    memory=8GB
    
    # Sets the number of virtual processors that the WSL 2 VM can use.
    # Replace <YourCPUCoreCount> with a value suitable for your system (e.g., 4, 6).
    processors=4
    
    # Specifies how much swap space will be added to the WSL 2 VM.
    # Replace <YourSwapValue> with a value appropriate for your workload (e.g., 4GB, 8GB).
    # A common rule of thumb is 1-2x your RAM if your RAM is <= 8GB, or 0.5-1x for more RAM.
    swap=8GB
    
    # Disables page reporting to Windows host, which can improve performance slightly.
    # This might use a bit more memory on the host, but reduces overhead.
    pageReporting=false
    
    # Sets the root folder for virtual hard disks. Ensure this path exists.
    # This is optional, but useful for relocating large VHDX files.
    # For example, if your C: drive is full.
    # autoMemoryReclaim=true # Enable if you experience high idle memory usage
    # virtualHardDiskPath=E:WSLvhdx
    

    The swap value configured here dictates the total virtual swap disk available to the WSL2 VM by the Windows host. The Linux kernel inside WSL2 will utilize this. Setting a dedicated swap file inside Ubuntu (Step 3) can still be beneficial for finer control or if this global setting isn't sufficient.

  3. Restart WSL2: For .wslconfig changes to take effect, you must shut down all running WSL2 instances.

    1. Open an Administrator PowerShell terminal.
    2. Run the command:
      wsl --shutdown
      
    3. Close the PowerShell window.
    4. Restart your WSL2 Ubuntu distribution by opening a new Ubuntu terminal.
  4. Verify New Allocation: Inside your Ubuntu terminal, run free -h again. You should now see the Swap row reflecting the value you set in .wslconfig.

    free -h
    # Example output after .wslconfig change
    #              total        used        free      shared  buff/cache   available
    # Mem:           8.0Gi       4.0Gi       2.0Gi       512Mi       2.0Gi       3.0Gi
    # Swap:          8.0Gi          0B       8.0Gi  <-- NOW YOU SHOULD SEE THIS!
    

3. Create/Resize a Dedicated Swap File within WSL2 Ubuntu (Optional, but Recommended)

Even with the .wslconfig swap parameter, some users prefer or require an explicit swap file managed directly by the Linux kernel inside the WSL2 distribution. This can be beneficial for specific workloads or to ensure full visibility of swap within Linux utilities.

  1. Check for Existing Swap File:

    sudo swapon --show
    

    If you see an entry like /swapfile, note its size. If it's too small, you can remove and recreate it, or if no swap file exists, proceed with creation.

  2. Disable Existing Swap (if resizing/recreating): If you're replacing an existing swap file, disable it first.

    sudo swapoff /swapfile
    

    (Replace /swapfile with the path shown by swapon --show if different).

  3. Create a New Swap File: Use fallocate for faster creation (preferred) or dd. Replace 4G with your desired size (e.g., 8G). A common recommendation is 1-2 times your available RAM or the amount specified in .wslconfig if you want them similar.

    # Using fallocate (preferred)
    sudo fallocate -l 4G /swapfile
    
    # OR using dd (if fallocate is not available)
    # sudo dd if=/dev/zero of=/swapfile bs=1M count=4096 # For 4GB (count = size in MB)
    
  4. Set Correct Permissions: The swap file must have restricted permissions for security.

    sudo chmod 600 /swapfile
    
  5. Set Up the Swap Area:

    sudo mkswap /swapfile
    
  6. Enable the Swap File:

    sudo swapon /swapfile
    
  7. Make Swap Persistent Across Restarts: Edit the /etc/fstab file to ensure your new swap file is enabled automatically every time your WSL2 instance starts.

    echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
    

    While beneficial, do not over-allocate swap. Using too much swap can lead to "thrashing" and significantly slow down your system, as disk I/O is much slower than RAM. Balance your swap size with your physical RAM and workload.

4. Tune Swappiness (Optional but Recommended)

The swappiness parameter controls the kernel's tendency to swap processes out of physical memory and onto the swap disk. A lower value means the kernel will try to keep processes in RAM longer.

  1. Check Current Swappiness:

    cat /proc/sys/vm/swappiness
    

    The default is 60.

  2. Set Swappiness Temporarily: For most modern systems with decent RAM, a swappiness value between 10 and 20 is often recommended to reduce disk I/O. For servers that need to aggressively keep RAM free, you might choose a higher value.

    sudo sysctl vm.swappiness=10
    
  3. Make Swappiness Persistent: Add the setting to /etc/sysctl.conf to apply it after reboots.

    echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
    

    Then, apply changes without rebooting:

    sudo sysctl -p
    

    Experiment with swappiness. For development machines with plenty of RAM, a lower value (e.g., 10-20) can make the system feel snappier by minimizing disk writes. For systems with limited RAM that run many background services, a slightly higher value (e.g., 30-40) might be better to prevent OOM errors.

5. Verify Configuration

After implementing the changes, confirm that your new swap configuration and swappiness settings are active.

  1. Reboot WSL2 (perform wsl --shutdown from PowerShell and restart Ubuntu).
  2. Check Memory and Swap:
    free -h
    
    Confirm the Swap total reflects your desired size.
  3. Check Active Swap Devices:
    swapon --show
    
    If you created an in-distro swap file, it should now appear here, with the correct size.
  4. Check Swappiness:
    cat /proc/sys/vm/swappiness
    
    Verify it matches the value you set.

Your WSL2 Ubuntu environment should now be significantly more robust and performant under load, thanks to an optimized swap memory configuration.

👨‍💻

Johnathon Wheeler

Senior Systems Architect & DevOps Engineer • Austin, TX

Connect on LinkedIn →

Johnathon has over 16 years of hands-on experience designing, debugging, and scaling Linux web hosting stacks, container clusters, and high-availability database architectures. Every guide on ButItWorkedLocal is independently tested against Debian 12, Ubuntu 24.04/22.04 LTS, Rocky Linux, and Docker environments to guarantee reproducibility in production.

🛡️

Our Production Verification Guarantee

Encountering a bug not covered here or running a non-standard kernel configuration? Our solutions are continually refined against real production incidents. Submit an environment trace for our editorial team to replicate.