Skip to content

How to make wsl2 alive in the background #10138

Closed

Description

@amuncx

Wsl2 will automatically shut down when the terminal is closed.I need it alive in the background.
Is there such a function in the configuration file, so that wsl2 can only be closed manually by running wsl --shutdown. If not, would you consider adding this feature.

Activity

  1. elsaco commented on May 25, 2023

    @elsaco

    @amunv WT has a headless feature (microsoft/terminal#14944) that might keep your WSL instance running.

  2. amuncx commented on May 26, 2023

    @amuncx
    Author

    @amunv WT has a headless feature (microsoft/terminal#14944) that might keep your WSL instance running.

    I don't understand it a bit, should I add "allowHeadless": true in setting.json
    As he said, there is no wt --headless or wt --hidden.

  3. aki-k commented on Jun 6, 2023

    @aki-k

    @amunv You can make it stay running with this setup: #10157 (comment)

  4. OneBlue commented on Jun 13, 2023

    @OneBlue
    Collaborator

    Thank you for reporting this @amunv. You can force WSL2 to keep running with:

    [wsl2]
    vmIdleTimeout=-1
    

    in %userprofile%/.wslconfig

  5. aki-k commented on Jun 14, 2023

    @aki-k

    vmIdleTimeout=-1

    I'm not sure why this is not documented at https://learn.microsoft.com/en-us/windows/wsl/wsl-config

    It just says

    The number of milliseconds that a VM is idle, before it is shut down. Only available for Windows 11.

  6. amuncx commented on Jun 14, 2023

    @amuncx
    Author

    Thank you for reporting this @amunv. You can force WSL2 to keep running with:

    [wsl2]
    vmIdleTimeout=-1
    

    in %userprofile%/.wslconfig

    This is not what I need. About ten seconds after closing the terminal, wsl enters the suspended state. At this time, the docker application cannot be used normally, and the system memory usage is reduced. The "vmIdleTimeout" option controls the survival time of vmmemwsl after wsl is suspended. During this time, when WT is turned on, wsl will run normally. I don't need this suspend state and control the time after suspend. What I need is that wsl suspend after about ten seconds, disable this suspend.
    [wsl2] vmIdleTimeout=120000 memory=2GB processors=2

  7. OneBlue commented on Jun 14, 2023

    @OneBlue
    Collaborator

    Thank you for reporting this @amunv. You can force WSL2 to keep running with:

    [wsl2]
    vmIdleTimeout=-1
    

    in %userprofile%/.wslconfig

    This is not what I need. About ten seconds after closing the terminal, wsl enters the suspended state. At this time, the docker application cannot be used normally, and the system memory usage is reduced. The "vmIdleTimeout" option controls the survival time of vmmemwsl after wsl is suspended. During this time, when WT is turned on, wsl will run normally. I don't need this suspend state and control the time after suspend. What I need is that wsl suspend after about ten seconds, disable this suspend. [wsl2] vmIdleTimeout=120000 memory=2GB processors=2

    Yes, that's exactly what vmIdleTimeout=-1 does. When set to -1, the WSL2 VM will never time out and WSL2 will keep running until wsl.exe --shutdown is called.

  8. aki-k commented on Jun 15, 2023

    @aki-k

    Blue (@OneBlue) Your solution does not work. I put

    [wsl2]
    vmIdleTimeout=-1
    

    into C:\Users\aki\.wslconfig and restarted WSL 2 VM.

    Then I installed apache2 in WSL 2 VM

    sudo apt-get install apache2
    sudo systemctl enable --now apache2
    

    I can see in "ss -tulpan | grep apache2" that it's listening on port 80.

    Then I load http://localhost/ on Windows host side Firefox and the Apache2 Ubuntu Default Page opens.

    I exit from WSL 2 VM with "exit".

    I have this loop running in another CMD prompt

    for /l %i in () do @( tasklist | findstr /i "vm wsl" & ping -n 3 127.0.0.1 >nul & echo --- )
    

    It lists the processes matching "vm" and "wsl".

    When I exit WSL 2 VM, the 2 wslhost.exe processes end after a short while.

    The Apache2 Ubuntu Default Page on the Windows host side Firefox stops responding at the same time.

  9. elsaco commented on Jun 15, 2023

    @elsaco

    aki-k vmIdleTimeout = -1 does keep the VM running after exiting the shell. You stated adding the setting then restarted WSL 2 VM. Make sure you restart the WSL service not only the VM. Run wsl --shutdown for the setting to take effect.

  10. aki-k commented on Jun 15, 2023

    @aki-k

    and restarted WSL 2 VM.

    means I exited the WSL 2 VM and ran wsl --shutdown in CMD prompt. Do I also need to restart lxssmanager?

  11. aki-k commented on Jun 15, 2023

    @aki-k

    After "exit" -> 2 wslhost.exe processes stop after a short while -> "bash" -> I can use "ps auxwwf | grep apache2" to see the process start-up time and they just started up. So the WSL 2 instance also started up again.

  12. 24 remaining items

  13. ulayera commented on Aug 21, 2025

    @ulayera

    This is the place where I learnt the most about wsl and the startup thing.

    I wanted to keep wsl alive on windows startup, so i added a Scheduled Task to run this bat:

    @echo off
    
    set WSL_UTF8=1
    
    goto main
    
    REM Function to check WSL status
    :check_status
    wsl -l --running | FINDSTR Ubuntu >nul 2>&1
    if %errorlevel% equ 0 (
        set "STATUS=running"
    ) else (
        set "STATUS=down"
    )
    goto :eof
    
    REM Function to start distro
    :start_distro
    wsl --exec dbus-launch true
    if %errorlevel% equ 0 (
        echo %DATE% %TIME% started
    ) else (
        echo %DATE% %TIME% failed to start (error code: %errorlevel%)
    )
    goto :eof
    
    REM Main logic
    :main
    call :check_status
    if "%STATUS%"=="running" (
        echo %DATE% %TIME% running
    ) else (
        echo %DATE% %TIME% down, trying to start
        call :start_distro
    )
    
    timeout /t 5 /nobreak >nul
    goto main
    

    run it with these params > X:\path\to\your\logs\wsl-keepalive.log 2>&1 so the stdout gets written in a file and you can troubleshoot if necessary

  14. hoffor commented on Nov 10, 2025

    @hoffor

    microsoft adding a 'solution' that doesn't actually work at all and outright ignoring user feedback, classic

    it's weird.. @reboot dbus-launch true as a cron job doesn't keep it alive. logging into a shell and entering dbus-launch true works.. @reboot bash -l -i -c dbus-launch true does not. haven't yet found a way to automate this

    no sleep infinity method has kept it alive for me

    at the very least, wsl --exec bash -c "dbus-launch true; echo hello" keeps it alive for me. so basically just add that before anything you run and it should stay alive. note that this is on win11 26200 wsl2 ubuntu 24.04

  15. deniznehlyadyuk commented on Nov 12, 2025

    @deniznehlyadyuk
  16. bhoppi commented on Nov 14, 2025

    @bhoppi

    microsoft adding a 'solution' that doesn't actually work at all and outright ignoring user feedback, classic

    it's weird.. @reboot dbus-launch true as a cron job doesn't keep it alive. logging into a shell and entering dbus-launch true works.. @reboot bash -l -i -c dbus-launch true does not. haven't yet found a way to automate this

    no sleep infinity method has kept it alive for me

    at the very least, wsl --exec bash -c "dbus-launch true; echo hello" keeps it alive for me. so basically just add that before anything you run and it should stay alive. note that this is on win11 26200 wsl2 ubuntu 24.04

    Based on your description, here is my personal analysis:

    When no user processes are running under the wsl's /init process (PID 2), it will terminate the WSL instance, regardless of how many other processes are running.

    It's important to note that when a WSL instance starts, it launches two shell processes: one controlled by PID 2 (referred to as Shell 1), and the other invoked by the login command during the typical Linux system user login process (referred to as Shell 2).

    Shell 1 runs first, executing the WSL system initialization commands. When it reaches the user login step, it hands over to systemd for user login, at which point Shell 2 runs.
    Shell 2 executes the user login related scripts (*profile, *rc, etc.), managed by PID 1, not PID 2. After execution, the process is interrupted, and Shell 1 regains control.
    Subsequent commands executed by the user in terminal all run in Shell 1.

    It can be shown that:
    Long-running processes managed by PID 2, including cmds executed by Shell 1, can keep the WSL instance running, for example:

    • wsl --exec bash -c "dbus-launch true; echo hello"
    • logging into a shell and entering dbus-launch true

    Long-running processes managed by PID 1, including cmds executed by Shell 2, cannot keep the WSL instance running, for example:

    • cmds (no matter dbus-launch true, sleep infinity, or others) written in *profile and *rc
    • @reboot * cron jobs
    • loginctl enable-linger mentioned by some other people

    Based on the above analysis, I will present a very simple and effective solution that I have tested (this method is a modification of Jeongwon Kim (@gardengim) 's keepwsl but a little more friendly).

    First, here is the content of keepwsl.service:

    [Unit]
    Description=Keep WSL instance alive
    
    [Service]
    Type=oneshot
    ExecStart=/mnt/c/Windows/System32/wsl.exe --exec dbus-launch true
    Restart=on-failure
    RestartSec=5
    
    [Install]
    WantedBy=default.target
    

    Put the file under ~/.config/systemd/user/, then run below commands:

    systemctl --user daemon-reload
    systemctl --user enable --now keepwsl
    

    That all, enjoy it!

  17. hoffor commented on Nov 18, 2025

    @hoffor

    my personal issue with the keepwsl.service is that it relies on a windows drive being mounted to run its command, but i tend to keep mine dismounted because i sometimes run into issues when they're mounted (for example, one app package during installation found some windows files and really convinced itself they were the linux files it was looking for)

    i suppose that could be bypassed by wrapping the wsl.exe command in a dismount-then-remount... not an elegant solution though and probably not in high demand

  18. hoffor commented on Nov 19, 2025

    @hoffor

    Jeongwon Kim (@gardengim) that is a possible solution yeah. i'm unfortunately stubborn and desire to isolate the distro's filesystem from my host's.. i think it stems from a fear i might rm -rf /* as a funny joke and then forget my windows drives are mounted

    ..yeah anyway LOL hmm i guess in that case i could send a signal to the windows environment in a different way (ssh, named pipe, creating/modifying a file in the distro and then having windows check for it, etc) and have it reactively execute the wsl dbus command. if i do anything like that i'll get back to you

  19. aki-k commented on Nov 19, 2025

    @aki-k

    Of course, a new systemd service is not needed. Just start your WSL 2 instance with the wsl.exe option '--exec dbus-launch true'.

  20. hoffor commented on Nov 20, 2025

    @hoffor

    set-and-forget solution to keep a distro alive (for if you don't always keep your windows drives mounted in it):

    1. in your distro: sudo crontab -e (choose nano if it asks)
    2. paste this at the end of the file: @reboot mkdir -p /dev/shm/wsl_ipc; chmod 777 /dev/shm/wsl_ipc; touch /dev/shm/wsl_ipc/trigger and save the file (ctrl+x -> y -> enter)
    3. back in windows, put this powershell script somewhere permanent and add it as a scheduled login task (run as admin, replace the filename with yours): schtasks /Create /TN "wsl_keepalive" /TR "conhost powershell -WindowStyle Hidden -NonInteractive -ExecutionPolicy Bypass \"C:\wsl_keepalive.ps1\"" /SC ONLOGON /F

    wsl_keepalive.ps1:

    $distro = "noble"
    $triggerFile = "\\wsl.localhost\$distro\dev\shm\wsl_ipc\trigger"
    $wslCmd = "wsl -d $distro -u root -e dbus-launch true"
    
    while ($true)
    {
    	$lines = $(wsl.exe --list --running)
    	foreach ($line in $lines)
    	{
    		$cleanedLine = $line -replace "\s\(Default\)", ""
    		if ($cleanedLine -ceq $distro)
    		{
    			if (Test-Path $triggerFile)
    			{
    				Start-Process -NoNewWindow -FilePath "cmd.exe" -ArgumentList "/c $wslCmd"
    				Remove-Item $triggerFile -ErrorAction SilentlyContinue
    			}
    			break
    		}
    	}
    	Start-Sleep -Seconds 1
    }
    
    

    set $distro to your distro name (case sensitive)

    you can modify the script to operate on multiple distros if you want, or you can just duplicate the script file with a different name

    open Task Scheduler if you ever wanna mess with it, or to run it hidden without logging out and back in

    test it:

    1. wsl -t yourdistro to terminate it
    2. wsl -d yourdistro to launch it and get a shell
    3. exit to ditch it and see if windows kills it
    4. if wsl --list --running shows it running after about 10 seconds, you're golden
  21. aki-k commented on Nov 20, 2025

    @aki-k

    Holy over-engineering, Batman!

  22. hoffor commented on Nov 20, 2025

    @hoffor

    Holy over-engineering, Batman!

    i agree that it shouldn't be necessary in the first place. it's only as engineered as required by the limitation we have no control over. pretty simple workaround overall but my wordiness can make it seem like more than it is

    in short:

    1. add a line to your crontab to create an empty file on distro boot
    2. schedule a powershell script on logon that checks for that file and execute the dbus command when it finds it, then deletes it

    saves you from having to exec the dbus command every time you restart your distro. for someone who does that a lot (for one reason or another) it's a life saver

  23. aki-k commented on Nov 21, 2025

    @aki-k

    This is all you need:

    wsl.exe --distribution Ubuntu-24.04 --exec dbus-launch true & wsl.exe --distribution Ubuntu-24.04
    
  24. aki-k commented on Nov 24, 2025

    @aki-k

    hoffor I received a bat signal and soon after that my e-mail box received this CMD batch script for starting and stopping a WSL 2 instance with '--exec dbus-launch true':

    @echo off
    
    if [%1]==[] goto usage
    
    setlocal enableDelayedExpansion
    
    set "_distro=Ubuntu-24.04"
    
    for %%a in (%*) do (
        if /i "%%a"=="start" (
            set "_op=start" & goto execute
        ) else if /i "%%a"=="stop" (
            set "_op=stop" & goto execute
        ) else (
            goto usage
        )
    )
    
    :execute
    if /i "%_op%"=="start" (
        wsl.exe --terminate %_distro%
        wsl.exe --distribution %_distro% --exec dbus-launch true & wsl.exe --distribution %_distro%
    ) else if /i "%_op%"=="stop" (
        wsl.exe --terminate %_distro%
    )
    endlocal
    goto :EOF
    
    :usage
    echo usage: needs either a start or stop argument
    endlocal
    
  25. hoffor commented on Nov 25, 2025

    @hoffor

    aki-k i boot and invoke commands from within my distro in different ways depending on what i'm doing. messing with batch scripts or remembering to manually type the dbus command (worse yet, forgetting to type it and wondering why things are broken) is what i had set out to avoid. i love my solution because it's a simple one-time setup for literally never having to think about this issue ever again. for a true brain-off solution to an issue that should have never existed, it's the end-all

  26. hasanfaesal commented on Dec 9, 2025

    @hasanfaesal

    https://blog.lecoteauverdoyant.co.uk/articles/wsl-keep-alive.html

    this solved my issue

    This works for me as well, I really appreciate it.
    Thank you very much.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions