NixOS on WSL2 Configuration Guide

This guide covers installing and configuring NixOS on Windows Subsystem for Linux 2 (WSL2) using this template, providing a full development environment that seamlessly integrates with Windows.

Table of Contents

  1. Overview
  2. Prerequisites
  3. Installation
  4. Configuration
  5. Windows Integration
  6. Development Environment
  7. Performance Optimization
  8. Troubleshooting
  9. Advanced Usage

Overview

NixOS on WSL2 provides a complete declarative Linux development environment that seamlessly integrates with Windows. This template includes comprehensive WSL2 support with specialized modules and optimizations.

Key Features

WSL2 Module System

The template includes dedicated WSL2 modules:

Benefits

Prerequisites

Windows Requirements

Hardware Requirements

Software Prerequisites

  1. Enable WSL 2:

    # Run as Administrator
    wsl --install
    # or
    dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
    dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
    
  2. Set WSL 2 as default:

    wsl --set-default-version 2
    
  3. Install Windows Terminal (recommended):

    • From Microsoft Store or GitHub releases

Installation

  1. Download the template:

    git clone https://github.com/yourusername/nixos-template
    cd nixos-template
    
  2. Run the installation script:

    # Run PowerShell as Administrator
    .\scripts\install-wsl2.sh
    
  3. Follow the prompts:

    • Choose username and password
    • Wait for installation to complete (10-30 minutes)

Manual Installation

  1. Download NixOS-WSL:

    wget https://github.com/nix-community/NixOS-WSL/releases/latest/download/nixos-wsl-installer.tar.gz
    
  2. Import the distribution:

    wsl --import NixOS-Template C:\WSL\NixOS-Template nixos-wsl-installer.tar.gz --version 2
    
  3. Copy template configuration:

    wsl -d NixOS-Template
    # Inside WSL:
    git clone https://github.com/yourusername/nixos-template /tmp/template
    sudo cp -r /tmp/template/hosts/wsl2-template/* /etc/nixos/
    sudo nixos-rebuild switch
    

Configuration

System Configuration

The main system configuration is in /etc/nixos/configuration.nix:

# Core WSL2 settings from nixos-wsl
wsl = {
  enable = true;
  defaultUser = "nixos";
  startMenuLaunchers = true;  # Add apps to Windows Start Menu
  interop = {
    includePath = true;       # Include Windows PATH in WSL PATH
    register = true;          # Register WSL interop
  };
  useWindowsDriver = true;    # Use Windows OpenGL driver for better GPU performance
  docker-desktop.enable = false; # Enable if using Docker Desktop
  usbip.enable = false;      # Enable for USB device access
};

# Template-specific WSL2 modules
modules.wsl = {
  interop = {
    enable = true;           # Windows application integration
    windowsApps = true;      # Enable Windows app aliases (explorer.exe, code.exe)
    clipboard = true;        # Bidirectional clipboard sharing
    fileAssociations = true; # Open files with Windows applications
  };

  networking = {
    enable = true;
    dnsConfig = "auto";      # "auto" | "wsl" | "custom"
    firewallConfig = "disabled"; # "disabled" | "minimal" | "standard"
    networkOptimizations = true; # TCP and network performance tuning
    portForwarding = {       # Custom port forwarding for development
      ssh = 22;
      web = 3000;
      api = 8080;
    };
  };

  optimization = {
    enable = true;
    memory = {
      swappiness = 10;       # Lower swap usage (0-100)
      cacheOptimization = true;
      hugepages = false;     # Enable for memory-intensive workloads
    };
    filesystem = {
      mountOptimizations = true; # Optimize Windows drive mounts
      tmpfsSize = "2G";      # Size for /tmp tmpfs
      noCOW = true;          # Disable copy-on-write for large files
    };
    services = {
      disableUnneeded = true; # Disable services not needed in WSL
      optimizeSystemd = true; # Faster boot and service management
    };
    development = {
      fastBuild = true;      # Optimize for development builds
      cacheNix = true;       # Nix store optimizations
    };
  };

  systemd = {
    enable = true;           # Systemd optimizations for WSL2
    networkOptimizations = true; # Network service optimizations
    serviceOptimizations = true; # General service optimizations
  };
};

Module Configuration Details

Windows Interop Module (modules.wsl.interop)

Controls Windows integration features:

Networking Module (modules.wsl.networking)

Optimizes network performance and configuration:

Optimization Module (modules.wsl.optimization)

Performance tuning for WSL2 environment:

Systemd Module (modules.wsl.systemd)

Systemd service optimizations:

User Configuration

Home Manager configuration is in ~/.config/home-manager/home.nix:

# Import role-based configurations
imports = [
  ../../home/roles/developer.nix
  ../../home/profiles/headless.nix
];

# WSL2-specific shell aliases
programs.zsh.shellAliases = {
  explorer = "explorer.exe";
  code = "code.exe";
  wsl-open = "explorer.exe .";
};

Customization

  1. Edit system configuration:

    sudo nano /etc/nixos/configuration.nix
    
  2. Edit user configuration:

    nano ~/.config/home-manager/home.nix
    
  3. Apply changes:

    sudo nixos-rebuild switch
    home-manager switch
    

Windows Integration

File System Access

Application Integration

# Open current directory in Windows Explorer
wsl-open .

# Edit file in VS Code
wsl-edit myfile.txt

# Run Windows applications
explorer.exe
notepad.exe file.txt
code.exe project/

Clipboard Integration

The template includes clipboard sharing between WSL and Windows:

# Copy to Windows clipboard
echo "text" | clip.exe

# In tmux/vim, clipboard operations work automatically

PATH Integration

Windows executables are available in WSL PATH:

# These work automatically
code .
explorer .
powershell.exe
cmd.exe

Development Environment

Included Development Tools

WSL2-Specific Utilities

The template includes custom utilities for WSL2 integration:

System Information and Monitoring

Windows Integration Utilities

Development Environment Helpers

Development Workflow

  1. Clone projects to WSL filesystem:

    cd ~
    git clone https://github.com/user/project.git
    cd project
    
  2. Use integrated development tools:

    # Open project in VS Code
    code .
    
    # Start development server
    npm run dev
    
    # Access from Windows browser: http://localhost:3000
    
  3. Container development:

    # Docker works with Windows Docker Desktop
    docker run -p 8080:80 nginx
    
    # Or use Podman
    podman run -p 8080:80 nginx
    

Project Structure

Recommended project organization:

~/Development/
├── projects/           # Main development projects
│   ├── web/           # Web development
│   ├── mobile/        # Mobile development
│   └── desktop/       # Desktop applications
├── tools/             # Development tools and utilities
└── scripts/           # Custom scripts and automation

Performance Optimization

WSL2 Configuration

Create or edit C:\Users\Username\.wslconfig:

[wsl2]
# Memory allocation (adjust based on your system)
memory=8GB
# Processor count
processors=4
# Swap file size
swap=2GB
# Networking mode
networkingMode=mirrored
# GUI applications
guiApplications=true

System Optimizations

The template includes several performance optimizations:

Performance Monitoring

# System information and performance
wsl-info
wsl-performance-tune

# Resource monitoring
htop
iotop
performance-monitor

Best Practices

  1. File Location: Keep development files on WSL filesystem (/home)
  2. Memory Management: Use wsl --shutdown periodically to free memory
  3. Network: Use wsl-network-diagnostics to troubleshoot connectivity
  4. Storage: Regular cleanup with nix-collect-garbage

Troubleshooting

Common Issues

WSL2 Won’t Start

  1. Check WSL status:

    wsl --status
    wsl --list --verbose
    
  2. Restart WSL service:

    # As Administrator
    Restart-Service LxssManager
    
  3. Reset WSL2:

    wsl --shutdown
    wsl --unregister NixOS-Template
    # Reinstall from backup
    

Network Issues

  1. Check network configuration:

    wsl-network-diagnostics
    
  2. Reset network settings:

    sudo systemctl restart systemd-networkd
    sudo systemctl restart systemd-resolved
    
  3. Windows network reset:

    # As Administrator
    netsh winsock reset
    netsh int ip reset
    

Performance Issues

  1. Check resource usage:

    performance-monitor
    htop
    
  2. Optimize WSL2 settings:

    wsl-performance-tune
    
  3. Free up memory:

    wsl --shutdown
    # Wait 8 seconds, then restart
    wsl -d NixOS-Template
    

GUI Applications

  1. Install VcXsrv or similar X server on Windows

  2. Set DISPLAY variable:

    export DISPLAY=$(cat /etc/resolv.conf | grep nameserver | awk '{print $2}'):0.0
    
  3. Test GUI application:

    # Install a simple GUI app
    nix-shell -p xeyes --run xeyes
    

Configuration Issues

NixOS Rebuild Fails

  1. Check configuration syntax:

    sudo nixos-rebuild dry-run
    
  2. Rollback to previous generation:

    sudo nixos-rebuild switch --rollback
    
  3. Clean Nix store:

    sudo nix-collect-garbage -d
    

Home Manager Issues

  1. Check configuration:

    home-manager build
    
  2. Reset Home Manager:

    rm -rf ~/.local/state/home-manager/gcroots
    home-manager switch
    

Getting Help

  1. Check system logs:

    sudo journalctl -u multi-user.target
    sudo journalctl -f  # Follow logs in real-time
    
  2. WSL logs:

    # In PowerShell
    Get-EventLog -LogName Application -Source "Microsoft-Windows-Subsystem-Linux"
    
  3. Template-specific diagnostics:

    wsl-systemd-status
    wsl-systemd-optimize
    

Advanced Usage

Custom Modules

Create custom WSL2-specific modules:

# modules/custom/wsl-dev.nix
{ config, lib, pkgs, ... }:
{
  # Custom development environment for WSL2
  environment.systemPackages = with pkgs; [
    # Your custom packages
  ];

  # Custom services
  systemd.user.services.my-dev-service = {
    # Service configuration
  };
}

Multiple WSL Distributions

You can run multiple NixOS instances:

# Export current installation
wsl --export NixOS-Template nixos-backup.tar

# Create new instance
wsl --import NixOS-Dev C:\WSL\NixOS-Dev nixos-backup.tar

# Customize each instance separately
wsl -d NixOS-Dev
# Edit /etc/nixos/configuration.nix with different settings

Integration with IDEs

Visual Studio Code

  1. Install WSL extension

  2. Open project in WSL:

    code .
    
  3. Configure VS Code settings for WSL development

JetBrains IDEs

  1. Use JetBrains Gateway for remote development
  2. Configure SSH connection to WSL2
  3. Set up project interpreter pointing to WSL2

Backup and Migration

Backup Configuration

# Backup system configuration
sudo cp -r /etc/nixos ~/nixos-backup

# Backup Home Manager configuration
cp -r ~/.config/home-manager ~/home-manager-backup

# Export WSL distribution
wsl --export NixOS-Template nixos-full-backup.tar

Migration

# On new system, import distribution
wsl --import NixOS-Template C:\WSL\NixOS-Template nixos-full-backup.tar

# Apply configurations
sudo nixos-rebuild switch
home-manager switch

Container Integration

Docker Desktop Integration

The template works with Docker Desktop for Windows:

# Docker commands work transparently
docker run hello-world
docker-compose up

Podman Alternative

Or use Podman for a fully Linux solution:

# Podman with similar Docker experience
podman run hello-world
podman-compose up

Networking

Port Forwarding

WSL2 handles port forwarding automatically, but for advanced cases:

# Manual port forwarding (if needed)
netsh interface portproxy add v4tov4 listenport=3000 listenaddress=0.0.0.0 connectport=3000 connectaddress=WSL_IP

Custom Networking

Configure custom networking in your NixOS configuration:

# Advanced network configuration
networking = {
  firewall = {
    enable = true;
    allowedTCPPorts = [ 22 80 443 8080 ];
  };

  # Custom DNS
  nameservers = [ "1.1.1.1" "8.8.8.8" ];
};

Resources

Contributing

To improve WSL2 support in this template:

  1. Fork the repository
  2. Make improvements to WSL2 modules or configuration
  3. Test thoroughly in WSL2 environment
  4. Submit a pull request with detailed description

Common areas for contribution: