Created
April 13, 2017 11:19
-
-
Save thebentern/261b26ccf28a804734d42f52f6c02f7b to your computer and use it in GitHub Desktop.
Create hosts file entry for docker dynamically by name
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Replace-HostEntry ($targetDns, $newIpAddress) { | |
$hostsPath = "$env:windir\System32\drivers\etc\hosts" | |
$hosts = Get-Content $hostsPath | |
$hosts = $hosts -replace "^.+$targetDns", "$newIpAddress $targetDns" | |
$hosts | Out-File $hostsPath -enc ascii | |
} | |
function Get-DockerIpByImageName($imageName) { | |
$container = docker ps | Select-String $imageName | |
if ($container) { | |
Write-Information "Found container $container" | |
$containerId = $container.ToString().SubString(0, 12) | |
docker inspect --format "{{ .NetworkSettings.Networks.nat.IPAddress }}" $containerId | |
} | |
else { | |
Write-Warning "No docker container found with image name $imageName" | |
} | |
} | |
function Set-DockerContainerHostEntry($containerImageName, $targetDns) { | |
$ipAddress = Get-DockerIpByImageName -imageName $containerImageName | |
if ($ipAddress) { | |
Write-Information "Found ip address for container at $ipAddress" | |
Replace-HostEntry -targetDns $targetDns -newIpAddress $ipAddress | |
Write-Information "Successfully set $targetDns entry in hosts file to $ipAddress" | |
} | |
else { | |
Write-Error "Could not retrieve ip address from docker with image name $containerImageName" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment