• about 12 min read

Docker Desktop Kubernetes on Windows won't start: the port-reservation / portproxy rabbit hole, diagnosed and fixed for good

When using the bundled Kubernetes in Docker Desktop for Windows, you can hit a maddening problem: after restarting Docker Desktop, the K8s cluster won’t come up. The error is usually the vague “Unable to start a cluster, try again”.

Search around and most fixes boil down to resetting the cluster — a costly move that wipes your data. After going through this several times, I’ve identified the two real culprits and built an automation that permanently fixes both. The whole procedure never resets the cluster and never loses data.

The two culprits

One: a portproxy rule squatting on 6443

If you ever set up a netsh port forwarding rule to reach the K8s API server from the outside, that rule is likely one of the culprits.

First, check for it:

netsh interface portproxy show all

If the output contains the port the K8s API server listens on (default 6443), the problem is basically confirmed:

  • A wildcard listener on 0.0.0.0:6443 blocks Docker Desktop from binding 127.0.0.1:6443 for itself;
  • So the apiserver never gets a chance to start, and Docker reports a cluster startup failure.

The quick workaround: delete the forward while K8s is stopped, and re-add it once the cluster is up.

# Delete the rule while K8s is stopped
netsh interface portproxy delete v4tov4 listenport=6443 listenaddress=0.0.0.0

# Add it back once the cluster is up
netsh interface portproxy add v4tov4 listenport=6443 listenaddress=0.0.0.0 connectport=6443 connectaddress=127.0.0.1

Two: Windows reserved port ranges (Hyper-V / winnat)

This one is stealthier and far more common. Hyper-V/WSL on Windows reserves a large batch of dynamic ports at boot; if 6443 happens to fall inside a reserved range, the system rejects Docker’s bind outright.

How to find out:

netsh int ipv4 show excludedportrange protocol=tcp

For example, in this output 6443 falls in 6347-6446:

Protocol tcp Port Exclusion Ranges

Start Port    End Port
----------    --------
      6247        6346
      6347        6446   <-- 6443 is in here
      6447        6546
      ...

And in Docker’s backend log (%LOCALAPPDATA%\Docker\log\host\com.docker.backend.exe.log) you’ll find an unmistakable error:

kubernetes failed to start: {"progressMessage":"exposing apiserver port", ...}
POST /forwards/expose: listen tcp 127.0.0.1:6443: bind: An attempt was made to
access a socket in a way forbidden by its access permissions.

You can also directly test whether the port is bindable:

Test-NetConnection 127.0.0.1 -Port 6443

Manual fix

1. Fix the reserved port range: stop winnat first (it briefly blips Hyper-V/WSL networking for 1–2 seconds), register 6443 as a persistent reservation, then restart winnat. Hyper-V won’t grab the port again afterwards.

net stop winnat
netsh int ipv4 add excludedportrange protocol=tcp startport=6443 numberofports=1 store=persistent
net start winnat

If the add fails with “the file is in use by another process”, the 6443 range is still held by Hyper-V — you must stop winnat before adding (order matters).

2. Fix the portproxy: as described above — delete the rule while K8s is stopped, add it back once started.

3. Restart Docker Desktop’s Kubernetes — it should come up normally now.

Automation: install once, self-heal on every boot

Doing it by hand a couple of times is fine; having to do it on every reboot isn’t. So I wrote two PowerShell scripts plus two scheduled tasks:

  • Reserve-ApiserverPort.ps1: at boot, registers 6443 as a persistent reservation (the root fix);
  • Watch-K8sPortProxy.ps1: a resident watchdog that adds the portproxy as soon as the apiserver is up, and removes it when it goes down.

Put both scripts in C:\ProgramData\DockerK8s\.

Script 1: Reserve-ApiserverPort.ps1

<#
.SYNOPSIS
    Ensures the Kubernetes apiserver port (default 6443) is persistently reserved
    so that Hyper-V/winnat does not grab it and Docker Desktop Kubernetes can bind it.

.DESCRIPTION
    Idempotent. On each run:
      1. Verifies administrator privileges.
      2. Tries to add a persistent excluded-port-range reservation for <Port>.
      3. If 127.0.0.1:<Port> is still not bindable (range owned by Hyper-V/winnat),
         recycles the winnat service (stop -> add reservation -> start) and retries.
      4. Verifies the port is bindable again.

    This script is safe to run repeatedly and safe to schedule at startup: when the
    reservation is already in place it only tries to (re)add it, which is harmless.

    It can also be dot-sourced (to load Invoke-ApiserverReservation into the caller),
    which is how Install.ps1 invokes it in the already-elevated session.

.PARAMETER Port
    Apiserver port. Default 6443.

.PARAMETER LogPath
    Log file path. Defaults to reserve.log next to this script.

.NOTES
    Compatible with Windows PowerShell 5.1 and PowerShell 7+.
#>

[CmdletBinding()]
param(
    [int]$Port = 6443,
    [string]$LogPath
)

function Write-ReserveLog {
    param(
        [Parameter(Mandatory)][string]$Message,
        [Parameter(Mandatory)][string]$Path
    )
    $line = '{0} [reserve] {1}' -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $Message
    try {
        # Always UTF-8 with BOM so any reader/editor detects the encoding.
        $utf8Bom = New-Object System.Text.UTF8Encoding($true)
        [System.IO.File]::AppendAllText($Path, $line + [Environment]::NewLine, $utf8Bom)
    }
    catch { }
    Write-Verbose $line
}

function Test-IsAdmin {
    return ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}

function Test-PortBindable {
    param([Parameter(Mandatory)][int]$PortNumber)
    $listener = $null
    try {
        $listener = New-Object System.Net.Sockets.TcpListener([System.Net.IPAddress]::Loopback, $PortNumber)
        $listener.Start()
        return $true
    }
    catch {
        return $false
    }
    finally {
        if ($null -ne $listener) {
            try { $listener.Stop() } catch { }
            $listener = $null
        }
    }
}

function Test-AnyListenerOnPort {
    param([Parameter(Mandatory)][int]$PortNumber)
    $listeners = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties().GetActiveTcpListeners()
    foreach ($ep in $listeners) {
        if ($ep.Port -eq $PortNumber) { return $true }
    }
    return $false
}

function Add-PersistentReservation {
    param(
        [Parameter(Mandatory)][int]$PortNumber,
        [Parameter(Mandatory)][string]$LogPath
    )
    $output = & netsh.exe int ipv4 add excludedportrange protocol=tcp startport=$PortNumber numberofports=1 store=persistent 2>&1
    $code = $LASTEXITCODE
    $text = ($output | Out-String).Trim()
    Write-ReserveLog -Message ("netsh add excludedportrange exit=$code out='$text'") -Path $LogPath
    if ($code -eq 0) { return $true }
    if ($text -match 'already exists|已存在|对象已存在|attribute is already') { return $true }
    return $false
}

function Invoke-ApiserverReservation {
    [CmdletBinding()]
    param(
        [int]$Port = 6443,
        [string]$LogPath
    )

    if (-not $LogPath) {
        $base = if ($PSScriptRoot) { $PSScriptRoot } else { $PWD.Path }
        $LogPath = Join-Path $base 'reserve.log'
    }

    Write-ReserveLog -Message ("start port=$Port log=$LogPath elevated=$(Test-IsAdmin)") -Path $LogPath

    if (-not (Test-IsAdmin)) {
        Write-ReserveLog -Message 'not running elevated; cannot reserve port' -Path $LogPath
        return $false
    }

    $reserved = Add-PersistentReservation -PortNumber $Port -LogPath $LogPath

    # Always verify by actually binding. If the port is already in use by a live
    # listener (e.g. the running apiserver), do NOT recycle winnat.
    if (-not (Test-PortBindable -PortNumber $Port)) {
        if (Test-AnyListenerOnPort -PortNumber $Port) {
            Write-ReserveLog -Message ("port $Port is in use by a listener; skipping winnat recycle") -Path $LogPath
            return $true
        }
        Write-ReserveLog -Message 'port not bindable; recycling winnat' -Path $LogPath
        & net.exe stop winnat 2>&1 | Out-Null
        Start-Sleep -Seconds 2
        $reserved = Add-PersistentReservation -PortNumber $Port -LogPath $LogPath
        & net.exe start winnat 2>&1 | Out-Null
        Start-Sleep -Seconds 2
    }

    $bindable = Test-PortBindable -PortNumber $Port
    Write-ReserveLog -Message ("result bindable=$bindable reserved=$reserved") -Path $LogPath
    return $bindable
}

# Run only when executed as a standalone script (skipped when dot-sourced).
if ($MyInvocation.InvocationName -ne '.') {
    $ok = Invoke-ApiserverReservation -Port $Port -LogPath $LogPath
    if ($ok) { exit 0 } else { exit 2 }
}

Script 2: Watch-K8sPortProxy.ps1

<#
.SYNOPSIS
    Resident watchdog that publishes the Docker Desktop Kubernetes apiserver
    (127.0.0.1:<Port>) on all host IPv4/IPv6 interfaces via netsh portproxy,
    but only while the apiserver is actually listening.

.DESCRIPTION
    Loop (default every 10s):
      * Checks whether the REAL apiserver owns a 127.0.0.1:<Port> listener. It must
        not be a plain TCP connect: our own wildcard portproxy (0.0.0.0/::) would
        satisfy that and cause a false "up".
      * If UP   -> idempotently adds v4tov4 (0.0.0.0 -> 127.0.0.1) and
                   v6tov4 (:: -> 127.0.0.1) portproxy rules.
      * If DOWN for FailThreshold consecutive checks -> removes any portproxy
                   rules for <Port>. This prevents a wildcard 0.0.0.0 listener
                   from blocking Docker's own 127.0.0.1 bind on the next start.
      * On startup, removes any stale portproxy left over from a previous boot
                   (portproxy rules persist across reboots and would otherwise
                   sit on 0.0.0.0:<Port> before Docker starts).

    Design notes:
      * Single-threaded, no queues/locks -> no deadlocks.
      * Listener enumeration only (no TIME_WAIT churn); no state grows unbounded
        -> no handle/memory leaks.
      * Log file is size-capped and rotated -> no unbounded disk growth.
      * Compatible with Windows PowerShell 5.1 and PowerShell 7+.

    Requires administrator privileges (netsh portproxy). Intended to run as
    SYSTEM via a scheduled task.

.PARAMETER Port
    Apiserver port. Default 6443.

.PARAMETER IntervalSeconds
    Seconds between probes. Default 10.

.PARAMETER FailThreshold
    Consecutive failed probes before removing the portproxy. Default 3.

.PARAMETER ConnectAddress
    Backend address the portproxy forwards to. Default 127.0.0.1.

.PARAMETER LogPath
    Log file path. Defaults to watch.log next to this script.

.PARAMETER MaxLogBytes
    Rotate the log once it exceeds this size. Default 1 MiB.
#>

[CmdletBinding()]
param(
    [int]$Port = 6443,
    [int]$IntervalSeconds = 10,
    [int]$FailThreshold = 3,
    [string]$ConnectAddress = '127.0.0.1',
    [string]$LogPath,
    [int]$MaxLogBytes = 1048576
)

$ErrorActionPreference = 'Continue'
if (-not $LogPath) {
    $base = if ($PSScriptRoot) { $PSScriptRoot } else { $PWD.Path }
    $LogPath = Join-Path $base 'watch.log'
}

function Write-Log {
    param([Parameter(Mandatory)][string]$Message)
    $line = '{0} [watch] {1}' -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $Message
    try {
        if ((Test-Path -LiteralPath $LogPath) -and `
            ((Get-Item -LiteralPath $LogPath).Length -gt $MaxLogBytes)) {
            $bak = "$LogPath.1"
            Move-Item -LiteralPath $LogPath -Destination $bak -Force -ErrorAction SilentlyContinue
        }
        $utf8Bom = New-Object System.Text.UTF8Encoding($true)
        [System.IO.File]::AppendAllText($LogPath, $line + [Environment]::NewLine, $utf8Bom)
    }
    catch { }
    Write-Verbose $line
}

function Test-ApiserverListening {
    # True only when the real apiserver holds 127.0.0.1:<Port> (Docker exposes it
    # with in_ip=127.0.0.1). Our own portproxy listens on 0.0.0.0/::, so it can
    # never be mistaken for the apiserver. GetActiveTcpListeners enumerates only
    # listeners (not TIME_WAIT), so it is fast and does not churn connections.
    param([Parameter(Mandatory)][int]$PortNumber)
    $loopbacks = @(
        [System.Net.IPAddress]::Loopback
        [System.Net.IPAddress]::IPv6Loopback
    )
    $listeners = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties().GetActiveTcpListeners()
    foreach ($ep in $listeners) {
        if ($ep.Port -ne $PortNumber) { continue }
        foreach ($addr in $loopbacks) {
            if ($ep.Address.Equals($addr)) { return $true }
        }
    }
    return $false
}

function Test-V4ProxyExists {
    param([Parameter(Mandatory)][int]$PortNumber)
    $pattern = '^\s*0\.0\.0\.0\s+' + [regex]::Escape([string]$PortNumber) + '\s+'
    foreach ($line in (& netsh.exe interface portproxy show v4tov4 2>$null)) {
        if ($line -match $pattern) { return $true }
    }
    return $false
}

function Test-V6ProxyExists {
    param([Parameter(Mandatory)][int]$PortNumber)
    $pattern = '^\s*(::|\*)\s+' + [regex]::Escape([string]$PortNumber) + '\s+'
    foreach ($line in (& netsh.exe interface portproxy show v6tov4 2>$null)) {
        if ($line -match $pattern) { return $true }
    }
    return $false
}

function Add-Proxy {
    param([Parameter(Mandatory)][int]$PortNumber)
    if (-not (Test-V4ProxyExists -PortNumber $PortNumber)) {
        & netsh.exe interface portproxy add v4tov4 listenport=$PortNumber listenaddress=0.0.0.0 connectport=$PortNumber connectaddress=$ConnectAddress 2>&1 | Out-Null
        Write-Log "added v4tov4 0.0.0.0:$PortNumber -> ${ConnectAddress}:$PortNumber (exit=$LASTEXITCODE)"
    }
    if (-not (Test-V6ProxyExists -PortNumber $PortNumber)) {
        & netsh.exe interface portproxy add v6tov4 listenport=$PortNumber listenaddress=:: connectport=$PortNumber connectaddress=$ConnectAddress 2>&1 | Out-Null
        Write-Log "added v6tov4 [::]:$PortNumber -> ${ConnectAddress}:$PortNumber (exit=$LASTEXITCODE)"
    }
}

function Remove-Proxy {
    param([Parameter(Mandatory)][int]$PortNumber)
    if (Test-V4ProxyExists -PortNumber $PortNumber) {
        & netsh.exe interface portproxy delete v4tov4 listenport=$PortNumber listenaddress=0.0.0.0 2>&1 | Out-Null
        Write-Log "removed v4tov4 for port $PortNumber (exit=$LASTEXITCODE)"
    }
    if (Test-V6ProxyExists -PortNumber $PortNumber) {
        & netsh.exe interface portproxy delete v6tov4 listenport=$PortNumber listenaddress=:: 2>&1 | Out-Null
        Write-Log "removed v6tov4 for port $PortNumber (exit=$LASTEXITCODE)"
    }
}

Write-Log "start pid=$PID port=$Port interval=${IntervalSeconds}s failThreshold=$FailThreshold"

# A portproxy rule persists across reboots and would occupy 0.0.0.0/<Port> before
# Docker starts, blocking its 127.0.0.1 bind. Remove any stale rule on startup
# unless the real apiserver is already listening.
if (-not (Test-ApiserverListening -PortNumber $Port)) {
    Remove-Proxy -PortNumber $Port
}

$failCount = 0
while ($true) {
    try {
        if (Test-ApiserverListening -PortNumber $Port) {
            $failCount = 0
            if (-not (Test-V4ProxyExists -PortNumber $Port)) {
                Write-Log 'apiserver is up; ensuring portproxy'
                Add-Proxy -PortNumber $Port
            }
        }
        else {
            if ($failCount -lt $FailThreshold) { $failCount++ }
            if ($failCount -ge $FailThreshold -and (Test-V4ProxyExists -PortNumber $Port)) {
                Write-Log 'apiserver is down; removing portproxy'
                Remove-Proxy -PortNumber $Port
            }
        }
    }
    catch {
        Write-Log ('loop error: ' + $_.Exception.Message)
    }

    Start-Sleep -Seconds $IntervalSeconds
}

Registering the scheduled tasks

Run once as administrator (the port reservation needs elevation):

# 1. Run the port reservation once
& "C:\ProgramData\DockerK8s\Reserve-ApiserverPort.ps1"

# 2. Register two scheduled tasks
$ps  = "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe"
$dir = "C:\ProgramData\DockerK8s"

$principal = New-ScheduledTaskPrincipal -UserId SYSTEM -LogonType ServiceAccount -RunLevel Highest
$settings  = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries `
    -StartWhenAvailable -ExecutionTimeLimit ([TimeSpan]::Zero) `
    -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1) -MultipleInstances IgnoreNew

Register-ScheduledTask -TaskName DockerK8s-ApiserverReserve -Force `
    -Action (New-ScheduledTaskAction -Execute $ps -Argument "-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$dir\Reserve-ApiserverPort.ps1`"") `
    -Trigger (New-ScheduledTaskTrigger -AtStartup) `
    -Principal $principal -Settings $settings

Register-ScheduledTask -TaskName DockerK8s-PortProxyGate -Force `
    -Action (New-ScheduledTaskAction -Execute $ps -Argument "-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$dir\Watch-K8sPortProxy.ps1`"") `
    -Trigger @((New-ScheduledTaskTrigger -AtStartup), (New-ScheduledTaskTrigger -AtLogOn)) `
    -Principal $principal -Settings $settings

Start-ScheduledTask -TaskName DockerK8s-PortProxyGate

Then verify:

kubectl get nodes
netsh interface portproxy show all
Get-Content "C:\ProgramData\DockerK8s\watch.log" -Encoding UTF8 -Tail 20

Within ~10 seconds after the cluster comes up, the watchdog automatically forwards 0.0.0.0:6443 (and [::]:6443 on IPv6) to 127.0.0.1:6443; when the cluster stops, it removes them again.

War stories

One: child processes spawned via Start-Process lose elevation

If an installer script launches a child script like this:

Start-Process powershell -Wait -ArgumentList '-File', $reserveScript

under some UAC configurations the child process drops the elevated token, gets caught by the script’s #requires -RunAsAdministrator guard, and the symptom is baffling: exit code 1, and the log file is never even created. You can lose hours on this with no visible cause.

The fix: don’t spawn a child. Dot-source the script in the already-elevated current session instead:

. $reserveScript
Invoke-ApiserverReservation -Port 6443

The script uses $MyInvocation.InvocationName -ne '.' to detect whether it’s dot-sourced or run standalone, and only exits when standalone — so it can be both reused by other scripts and invoked directly by a scheduled task.

Two: portproxy rules survive reboots (the sneakiest one)

Rules added with netsh interface portproxy add are persistent — they outlive a reboot. If such a rule occupies 0.0.0.0:6443 before Docker starts, you trigger the “exposing apiserver port / bind forbidden” error all over again.

Worse: if the watchdog checks whether the apiserver is alive by opening a plain TCP connection to 127.0.0.1:6443, that connection gets served by the watchdog’s own 0.0.0.0 wildcard listener, producing a false “up” — so the rule is never cleaned up and the incident repeats on every reboot.

Two things fix it:

  1. Clean up stale rules at startup so leftovers from a previous boot don’t block the bind;
  2. Distinguish the real apiserver by its listening address: Docker exposes the apiserver with in_ip=127.0.0.1, so the real one binds 127.0.0.1:6443, while a portproxy only ever listens on 0.0.0.0/::. Just check for a 127.0.0.1:6443 listener — and this API doesn’t enumerate TIME_WAIT, so there’s no connection churn:
[System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties().GetActiveTcpListeners() |
    Where-Object { $_.Port -eq 6443 -and $_.Address.Equals([System.Net.IPAddress]::Loopback) }

Three: garbled log output — 鍙︿竴涓…

System tools like netsh emit output in the system’s local code page (GBK/936 on Chinese Windows). If you append it into a UTF-8 log and later read that log as GBK, you get mojibake like 鍙︿竴涓….

How to handle it:

  • Always write logs as UTF-8 with BOM (UTF8Encoding($true) + AppendAllText); every editor detects it;
  • Print only ASCII to the console; don’t push localized strings straight to the terminal;
  • Specify the encoding explicitly when reading: Get-Content xxx.log -Encoding UTF8.

Four: SYSTEM-owned scheduled tasks are invisible without elevation

Tasks registered as SYSTEM / highest privilege have a default security descriptor that lets only administrators read them. Open Task Scheduler without elevation and the two tasks don’t appear at all — querying can even return “Access denied”.

They show up under the root of the Task Scheduler Library (not in a subfolder), when you open it as administrator:

  • DockerK8s-ApiserverReserve
  • DockerK8s-PortProxyGate

Five: keep the resident script leak- and deadlock-proof

The watchdog runs forever, so these were deliberate design choices:

  • Single-threaded, lock-free, queue-free — no deadlocks possible;
  • TcpClients and WaitHandles from each probe are closed in finally, no handle leaks;
  • No accumulating state, capped failure counter — stable memory;
  • The log rotates past 1 MiB, so disk doesn’t grow;
  • The scheduled task sets -MultipleInstances IgnoreNew, so no duplicates pile up.

Uninstall / rollback

Stop-ScheduledTask -TaskName DockerK8s-PortProxyGate -ErrorAction SilentlyContinue
Unregister-ScheduledTask -TaskName DockerK8s-PortProxyGate -Confirm:$false
Unregister-ScheduledTask -TaskName DockerK8s-ApiserverReserve -Confirm:$false

netsh interface portproxy delete v4tov4 listenport=6443 listenaddress=0.0.0.0
netsh interface portproxy delete v6tov4 listenport=6443 listenaddress=::

Remove-Item "C:\ProgramData\DockerK8s" -Recurse -Force

# Optional: remove the port reservation
netsh int ipv4 delete excludedportrange protocol=tcp startport=6443 numberofports=1 store=persistent
jcbl1
jcbl1 Software Engineer