Unix Sockets

Bind to a Unix domain socket instead of TCP for local reverse proxy performance.

Prerequisites: see Introduction.

Full source

File: pwsh/tutorial/examples/7.5-Unix-Sockets.ps1

<#
        Sample: Kestrun Server over a Unix Domain Socket
        Demonstrates binding to a Unix domain socket for local IPC instead of a TCP port.
        File:    7.5-Unix-Sockets.ps1
#>
param(
    [string]$SocketPath = 'kestrun-demo.sock'
)

# 1. (Optional) Logging pipeline so we see events
New-KrLogger |
    Add-KrSinkConsole |
    Register-KrLogger -Name 'console' -SetAsDefault | Out-Null

# 2. Create server host
New-KrServer -Name 'Endpoints Unix'

# 3. Add Unix socket listener (auto unlinks existing file if present)
Add-KrListenUnixSocket -SocketPath (Join-Path -Path $([System.IO.Path]::GetTempPath()) -ChildPath $SocketPath)

# 5. Finalize configuration
Enable-KrConfiguration

# 6. Map GET /ux route
Add-KrMapRoute -Verbs Get -Pattern '/ux' -ScriptBlock {
    Write-KrLog -Level Debug -Message 'Unix socket route'
    Write-KrTextResponse -InputObject 'Hello via unix socket'
}

# 7. Informational log
Write-KrLog -Level Information -Message 'Unix socket listener active.'

# 8. Start server (Ctrl+C to stop)
Start-KrServer -CloseLogsOnExit

Step-by-step

  1. Check OS (warn/skip on Windows).
  2. Create server.
  3. Add Unix socket listener with Add-KrListenUnixSocket.
  4. Enable configuration.
  5. Map /ux route.
  6. Start server.

Try it

In another shell (after the server is running):

Invoke-WebRequest -UnixSocket $(Join-Path -Path $env:TEMP -ChildPath 'kestrun-demo.sock') -Method GET -Uri 'http://localhost/ux'

Expected (truncated):

StatusCode : 200
Content    : Hello via unix socket

If you get 404 verify the route is /ux and the socket path matches the one in the script.

Reverse proxy (nginx) snippet

location / {
    proxy_pass http://unix:/tmp/kestrun-demo.sock;
}

References

Troubleshooting

Symptom Cause Fix
Socket file remains Crash / abrupt stop Manually remove stale file
Proxy 502 Wrong socket path Match proxy config to -SocketPath

See also: Routes · Logging


Previous / Next