Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

How to acces transparently Linux container from Windows host LAN with Docker Desktop / Hyper-V / MobyLinuxVM

How to acces transparently Linux container from Windows host LAN with Docker Desktop / Hyper-V / MobyLinuxVM ??

My wish :

  • A Windows 10 host with LAN on subnet 169.254.0.0
  • Linux containers (Docker Desktop 18.09.1 / Hyper-V / MobyLinuxVM)
  • Linux containers in the same LAN as Windows host
  • No NAT between Windows host and Linux containers (transparent network)
  • Shared directory between Linux containers and Windows host
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

After one week of investigations on how to acces transparently Linux container from a Windows host private LAN with MobyLinuxVM Hyper-V, and after a lot of readings of forums, here is my how to :

  • On Windows host, install a new Ethernet device Microsoft Loopback KM-TEST
  • Configure a static IP on this device 169.254.0.1
  • On Docker Desktop configuration page, choose Network Subnet 169.254.0.0
  • Replace the code in C:Program FilesDockerDocker esourcesMobyLinux.ps1 by the following code : (all the modifications are prefixed by "# BLT") (replace "XXXXXXXXXXX" by the description of the Microsoft KM-TEST Ethernet device in your language)

Param(
    [string] $VmName = "MobyLinuxVM",
    [string] $IsoFile = ".docker-for-win.iso",
    # BLT
    # [string] $SwitchName = "DockerNAT",
    [string] $SwitchName = "Custom",
    [string] $VhdPathOverride = $null,
    [long] $VhdSize = 64*1000*1000*1000,
    [string] $confIsoFile = $null,
    [string] $DockerIsoFile = $null,
    [Parameter(ParameterSetName='Create',Mandatory=$false)][switch] $Create,
    [Parameter(ParameterSetName='Create',Mandatory=$false)][int] $CPUs = 2,
    [Parameter(ParameterSetName='Create',Mandatory=$false)][long] $Memory = 2048,
    [Parameter(ParameterSetName='Create',Mandatory=$false)][string] $SwitchSubnetAddress = "10.0.75.0",
    [Parameter(ParameterSetName='Create',Mandatory=$false)][int] $SwitchSubnetMaskSize = 24,
    [Parameter(ParameterSetName='Destroy',Mandatory=$false)][switch] $Destroy,
    [Parameter(ParameterSetName='Destroy',Mandatory=$false)][switch] $KeepVolume,
    [Parameter(ParameterSetName='Start',Mandatory=$false)][switch] $Start,
    [Parameter(ParameterSetName='Stop',Mandatory=$false)][switch] $Stop
)

Write-Output "Script started at $(Get-Date -Format "HH:mm:ss.fff")"

# This makes sure the system modules can be imported
$env:PSModulePath = [Environment]::GetEnvironmentVariable('PSModulePath','Machine')

# Make sure we stop at Errors unless otherwise explicitly specified
$ErrorActionPreference = "Stop"
$ProgressPreference = "SilentlyContinue"

# Explicitly disable Module autoloading and explicitly import the
# Modules this script relies on. This is not strictly necessary but
# good practise as it prevents arbitrary errors
$PSModuleAutoloadingPreference = 'None'

Import-Module Microsoft.PowerShell.Utility
Import-Module Microsoft.PowerShell.Management
Import-Module Hyper-V
Import-Module NetAdapter
Import-Module NetTCPIP

Write-Output "Modules loaded at $(Get-Date -Format "HH:mm:ss.fff")"

function Get-Vhd-Root {
    if($VhdPathOverride){
        return $VhdPathOverride
    }
    # Default location for VHDs
    $VhdRoot = "$((Hyper-VGet-VMHost -ComputerName localhost).VirtualHardDiskPath)".TrimEnd("")

    # Where we put Moby
    return "$VhdRoot$VmName.vhdx"
}

function New-Switch {
    $ipParts = $SwitchSubnetAddress.Split('.')
    [int]$switchIp3 = $null
    [int32]::TryParse($ipParts[3] , [ref]$switchIp3 ) | Out-Null
    $Ip0 = $ipParts[0]
    $Ip1 = $ipParts[1]
    $Ip2 = $ipParts[2]
    $Ip3 = $switchIp3 + 1
    $switchAddress = "$Ip0.$Ip1.$Ip2.$Ip3"

    # BLT
    # $vmSwitch = Hyper-VGet-VMSwitch $SwitchName -SwitchType Internal -ea SilentlyContinue
    $vmSwitch = Hyper-VGet-VMSwitch $SwitchName -ea SilentlyContinue
    $vmNetAdapter = Hyper-VGet-VMNetworkAdapter -ManagementOS -SwitchName $SwitchName -ea SilentlyContinue
    if ($vmSwitch -and $vmNetAdapter) {
        Write-Output "Using existing Switch: $SwitchName"
    } else {
        Write-Output "Creating Switch: $SwitchName..."

        Hyper-VRemove-VMSwitch $SwitchName -Force -ea SilentlyContinue
        # BLT
        # Hyper-VNew-VMSwitch $SwitchName -SwitchType Internal -ea SilentlyContinue | Out-Null
        Hyper-VNew-VMSwitch $SwitchName -NetAdapterInterfaceDescription "XXXXXXXXXXX Microsoft KM-TEST" -ea SilentlyContinue | Out-Null
        $vmNetAdapter = Hyper-VGet-VMNetworkAdapter -ManagementOS -SwitchName $SwitchName

        Write-Output "Switch created."
    }

    # Make sure there are no lingering net adapter
    $netAdapters = Get-NetAdapter | ? { $_.Name.StartsWith("vEthernet ($SwitchName)") }
    if (($netAdapters).Length -gt 1) {
        Write-Output "Disable and rename invalid NetAdapters"

        $now = (Get-Date -Format FileDateTimeUniversal)
        $index = 1
        $invalidNetAdapters =  $netAdapters | ? { $_.DeviceID -ne $vmNetAdapter.DeviceId }

        foreach ($netAdapter in $invalidNetAdapters) {
            $netAdapter `
                | Disable-NetAdapter -Confirm:$false -PassThru `
                | Rename-NetAdapter -NewName "Broken Docker Adapter ($now) ($index)" `
                | Out-Null

            $index++
        }
    }

    # Make sure the Switch has the right IP address
    $networkAdapter = Get-NetAdapter | ? { $_.DeviceID -eq $vmNetAdapter.DeviceId }
    if ($networkAdapter | Get-NetIPAddress -IPAddress $switchAddress -ea SilentlyContinue) {
        $networkAdapter | Disable-NetAdapterBinding -ComponentID ms_server -ea SilentlyContinue
        $networkAdapter | Enable-NetAdapterBinding  -ComponentID ms_server -ea SilentlyContinue
        Write-Output "Using existing Switch IP address"
        return
    }

    # BLT
    #$networkAdapter | Remove-NetIPAddress -Confirm:$false -ea SilentlyContinue
    #$networkAdapter | Set-NetIPInterface -Dhcp Disabled -ea SilentlyContinue
    #$networkAdapter | New-NetIPAddress -AddressFamily IPv4 -IPAddress $switchAddress -PrefixLength ($SwitchSubnetMaskSize) -ea Stop | Out-Null

    $networkAdapter | Disable-NetAdapterBinding -ComponentID ms_server -ea SilentlyContinue
    $networkAdapter | Enable-NetAdapterBinding  -ComponentID ms_server -ea SilentlyContinue
    Write-Output "Set IP address on switch"
}

function Remove-Switch {
    Write-Output "Destroying Switch $SwitchName..."

    # Let's remove the IP otherwise a nasty bug makes it impossible
    # to recreate the vswitch
    $vmNetAdapter = Hyper-VGet-VMNetworkAdapter -ManagementOS -SwitchName $SwitchName -ea SilentlyContinue
    if ($vmNetAdapter) {
        $networkAdapter = Get-NetAdapter | ? { $_.DeviceID -eq $vmNetAdapter.DeviceId }
        $networkAdapter | Remove-NetIPAddress -Confirm:$false -ea SilentlyContinue
    }

    Hyper-VRemove-VMSwitch $SwitchName -Force -ea SilentlyContinue
}

function New-MobyLinuxVM {
    if (!(Test-Path $IsoFile)) {
        Fatal "ISO file at $IsoFile does not exist"
    }

    $CPUs = [Math]::min((Hyper-VGet-VMHost -ComputerName localhost).LogicalProcessorCount, $CPUs)

    $vm = Hyper-VGet-VM $VmName -ea SilentlyContinue
    if ($vm) {
        if ($vm.Length -ne 1) {
            Fatal "Multiple VMs exist with the name $VmName. Delete invalid ones or reset Docker to factory defaults."
        }
    } else {
        Write-Output "Creating VM $VmName..."
        $vm = Hyper-VNew-VM -Name $VmName -Generation 2 -NoVHD
        $vm | Hyper-VSet-VM -AutomaticStartAction Nothing -AutomaticStopAction ShutDown -CheckpointType Disabled
    }

    if ($vm.Generation -ne 2) {
            Fatal "VM $VmName is a Generation $($vm.Generation) VM. It should be a Generation 2."
    }

    if ($vm.State -ne "Off") {
        Write-Output "VM $VmName is $($vm.State). Cannot change its settings."
        return
    }

    Write-Output "Setting CPUs to $CPUs and Memory to $Memory MB"
    $Memory = ([Math]::min($Memory, ($vm | Hyper-VGet-VMMemory).MaximumPerNumaNode))
    $vm | Hyper-VSet-VM -MemoryStartupBytes ($Memory*1024*1024) -ProcessorCount $CPUs -StaticMemory

    Ensure-VHD-Path($vm)

    $vmNetAdapter = $vm | Hyper-VGet-VMNetworkAdapter
    if (!$vmNetAdapter) {
        Write-Output "Attach Net Adapter"
        $vmNetAdapter = $vm | Hyper-VAdd-VMNetworkAdapter -Passthru
    }

    Write-Output "Connect Internal Switch $SwitchName"
    # BLT
    # $vmNetAdapter | Hyper-VConnect-VMNetworkAdapter -VMSwitch $(Hyper-VGet-VMSwitch -ComputerName localhost $SwitchName -SwitchType Internal)
    $vmNetAdapter | Hyper-VConnect-VMNetworkAdapter -VMSwitch $(Hyper-VGet-VMSwitch -ComputerName localhost $SwitchName)

    if ($vm.DVDDrives) {
        Write-Output "Remove existing DVDs"
        Hyper-VRemove-VMDvdDrive $vm.DVDDrives -ea SilentlyContinue
    }

    Write-Output "Attach DVD $IsoFile"
    $vm | Hyper-VAdd-VMDvdDrive -Path $IsoFile
    $iso = $vm | Hyper-VGet-VMFirmware | select -ExpandProperty BootOrder | ? { $_.FirmwarePath.EndsWith("Scsi(0,1)") }
    $vm | Hyper-VSet-VMFirmware -EnableSecureBoot Off -FirstBootDevice $iso

    $vm | Hyper-VSet-VMComPort -number 1 -Path "\.pipedocker$VmName-com1"

    # Enable only required VM integration services
    $intSvc = @()
    $intSvc += "Microsoft:$($vm.Id)84EAAE65-2F2E-45F5-9BB5-0E857DC8EB47" # Heartbeat
    $intSvc += "Microsoft:$($vm.Id)9F8233AC-BE49-4C79-8EE3-E7E1985B2077" # Shutdown
    $intSvc += "Microsoft:$($vm.Id)2497F4DE-E9FA-4204-80E4-4B75C46419C0" # TimeSynch
    $vm | Hyper-VGet-VMIntegrationService | ForEach-Object {
        if ($intSvc -contains $_.Id) {
            Hyper-VEnable-VMIntegrationService $_
            Write-Output "Enabled $($_.Name)"
        } else {
            Hyper-VDisable-VMIntegrationService $_
            Write-Output "Disabled $($_.Name)"
        }
    }
    $vm | Hyper-VDisable-VMConsoleSupport

    Write-Output "VM created."
}

function Remove-MobyLinuxVM {
    Write-Output "Removing VM $VmName..."

    Hyper-VRemove-VM $VmName -Force -ea SilentlyContinue

    if (!$KeepVolume) {
        $VmVhdFile = Get-Vhd-Root
        Write-Output "Delete VHD $VmVhdFile"
        Remove-Item $VmVhdFile -ea SilentlyContinue
    }
}

function Start-MobyLinuxVM {
    Write-Output "Starting VM $VmName..."

    $vm = Hyper-VGet-VM $VmName -ea SilentlyContinue

    if ($vm.DVDDrives) {
        Write-Output "Remove existing DVDs"
        Hyper-VRemove-VMDvdDrive $vm.DVDDrives -ea SilentlyContinue
    }

    Write-Output "Attach DVD $IsoFile"
    $vm | Hyper-VAdd-VMDvdDrive -ControllerNumber 0 -ControllerLocation 1 -Path $IsoFile

    if ((Get-Item $confIsoFile).length -gt 0) {
        Write-Output "Attach Config ISO $confIsoFile"
        if (($vm | Get-VMScsiController).length -le 1) {
            $vm | Add-VMScsiController
        }
        $vm | Hyper-VAdd-VMDvdDrive -ControllerNumber 1 -ControllerLocation 1 -Path $confIsoFile
    }
    if ((Get-Item $DockerIsoFile).length -gt 0) {
        Write-Output "Attach Docker ISO $DockerIsoFile"
        if (($vm | Get-VMScsiController).length -le 2) {
            $vm | Add-VMScsiController
        }
        $vm | Hyper-VAdd-VMDvdDrive -ControllerNumber 2 -ControllerLocation 1 -Path $DockerIsoFile
    }

    Ensure-VHD-Path($vm)

    $iso = $vm | Hyper-VGet-VMFirmware | select -ExpandProperty BootOrder | ? { $_.FirmwarePath.EndsWith("Scsi(0,1)") }

    $vm | Hyper-VSet-VMFirmware -EnableSecureBoot Off -BootOrder $iso

    Hyper-VStart-VM -VMName $VmName
}

function Ensure-VHD-Path {
    Param($vm)

    $VmVhdFile = Get-Vhd-Root
    $vhd = Get-VHD -Path $VmVhdFile -ea SilentlyContinue
    if (!$vhd) {
        Write-Output "Creating dynamic VHD: $VmVhdFile"
        $vhd = New-VHD -ComputerName localhost -Path $VmVhdFile -Dynamic -SizeBytes $VhdSize -BlockSizeBytes 1MB
    }

    if ($vm.HardDrives.Path -ne $VmVhdFile) {
        if ($vm.HardDrives) {
            Write-Output "Remove existing VHDs"
            Hyper-VRemove-VMHardDiskDrive $vm.HardDrives -ea SilentlyContinue
        }

        Write-Output "Attach VHD $VmVhdFile"
        $vm | Hyper-VAdd-VMHardDiskDrive -Path $VmVhdFile
    }
}

function Stop-MobyLinuxVM {
    $vms = Hyper-VGet-VM $VmName -ea SilentlyContinue
    if 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...