WSL2部署Docker应用,服务器重启后实例无法持久运行的解决方案咨询
WSL2部署Docker应用,服务器重启后实例无法持久运行的解决方案咨询
问题背景
我们在客户的Windows Server 2022服务器上部署了一个Docker应用,采用的架构是WSL2(Ubuntu-20.04)+ 直接安装在WSL2内的Docker(未使用Docker Desktop)。由于客户的安全策略,服务器会定期重启,我们需要确保重启后Docker应用能自动恢复运行。
目前我们已经做了这些配置:
- Docker Compose文件中,所有容器都设置了
restart: always参数 - 编写了一段PowerShell启动脚本,通过Windows任务计划程序配置为服务器重启时触发执行
脚本执行日志显示没有报错,但实际问题是:WSL实例无法在后台持久运行——必须手动登录服务器并打开WSL终端后,应用才能正常对外提供服务。
现有启动脚本
以下是我们当前使用的PowerShell脚本:
$distro = "Ubuntu-20.04" $ports = @(80,443) $log = "C:\scripts\wsl-startup.log" function Log($m){ $ts=(Get-Date).ToString("s"); Add-Content -Path $log -Value "[$ts] $m" } try { Log "=== Boot script start ===" Start-Sleep 45 Try { Set-Service iphlpsvc -StartupType Automatic } Catch {} Start-Service iphlpsvc -ErrorAction SilentlyContinue # Start the distro headlessly (keepalive + docker should keep it running) Log "Starting WSL distro" wsl -d $distro -- true | Out-Null # Get WSL IPv4 $wslIp = $null for ($i=0; $i -lt 12 -and -not $wslIp; $i++) { $ipRaw = (wsl -d $distro hostname -I) 2>$null Log ("hostname -I: '{0}'" -f $ipRaw) $wslIp = ([regex]::Match($ipRaw,'\d+\.\d+\.\d+\.\d+')).Value if (-not $wslIp) { Start-Sleep 5 } } if (-not $wslIp) { Log "ERROR: Could not determine WSL IPv4"; exit 1 } Log ("WSL IPv4 = {0}" -f $wslIp) foreach ($p in $ports) { Log ("Setting portproxy :{0} -> {1}:{0}" -f $p, $wslIp) netsh interface portproxy delete v4tov4 listenaddress=0.0.0.0 listenport=$p 2>$null | Out-Null netsh interface portproxy add v4tov4 listenaddress=0.0.0.0 listenport=$p connectaddress=$wslIp connectport=$p | Out-Null } Log "=== Boot script end ===" exit 0 } catch { Log ("EXCEPTION: {0}" -f $_.Exception.Message); exit 1 }
我们的疑问
- 为什么当前脚本启动WSL后,实例无法在后台持久运行?是否是因为
wsl -d $distro -- true这种方式启动的实例会在命令执行完后退出? - 有没有更可靠的方法让WSL2实例在服务器重启后自动后台启动并持久运行,确保Docker服务和容器自动恢复?
- 针对Windows Server环境下的WSL2自动启动场景,有没有其他需要注意的配置点(比如服务依赖、权限设置等)?
希望有经验的朋友能帮忙分析问题原因,或者提供更优的实现方案,感谢!




