Windows containers by hand. Part 2: Giving containers names and addresses
All parts of the series “Windows containers by hand”In the first part we installed containerd and worked out what can be done with a single container: networking, ports, host folders and files, limits, isolation levels. Today there will be two containers, and one of them will need to reach the other by name. We will look at the ways to do that and try them one by one until we find one that works with any start order.
Everything you will need is in the 02-names folder of the repository.
Two containers on one network
Let's start two containers: web with Microsoft's ASP.NET sample, which listens on port 8080, and client, a Nano Server that does nothing while we go into it with exec:
nerdctl run -d --name web -p 8080:8080 mcr.microsoft.com/dotnet/samples:aspnetapp-nanoserver-ltsc2025
nerdctl run -d --name client mcr.microsoft.com/windows/nanoserver:ltsc2025 ping -t localhost
ping -t pings the container itself endlessly; it is just a way to keep it running. To reach web, we need its address. On Windows nerdctl inspect web does not show the address (the NetworkSettings.IPAddress field is empty), so we will ask the containers themselves:
function Get-ContainerIp($name) { ((nerdctl exec $name cmd /c "ipconfig | findstr IPv4") -split ':')[-1].Trim() }
$webIp = Get-ContainerIp web
$clientIp = Get-ContainerIp client
"web=$webIp client=$clientIp"
nerdctl exec client ping -n 3 $webIp
nerdctl exec client curl.exe -sS -o NUL -w "%{http_code}`n" "http://${webIp}:8080/"
nerdctl exec web cmd /c ping -n 2 $clientIp
web=172.30.252.180 client=172.30.133.157
Pinging 172.30.252.180 with 32 bytes of data:
Reply from 172.30.252.180: bytes=32 time<1ms TTL=128
Reply from 172.30.252.180: bytes=32 time<1ms TTL=128
Reply from 172.30.252.180: bytes=32 time<1ms TTL=128
Ping statistics for 172.30.252.180:
Packets: Sent = 3, Received = 3, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms
200
Pinging 172.30.133.157 with 32 bytes of data:
Reply from 172.30.133.157: bytes=32 time<1ms TTL=128
Reply from 172.30.133.157: bytes=32 time<1ms TTL=128
Ping statistics for 172.30.133.157:
Packets: Sent = 2, Received = 2, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms
The containers see each other directly: ping works in both directions, and a web request (HTTP is the protocol a browser uses to fetch pages) to web on port 8080 returned code 200. TTL, a counter that every router on a packet's path decrements, arrived untouched (128, the Windows initial value): there is no router between the containers, they are in one subnet behind one virtual switch. No port publishing is needed for this: -p is only for access from outside the host.
And now by name:
nerdctl exec client curl.exe -sS -m 5 -o NUL http://web:8080/
curl: (6) Could not resolve host: web
time="2026-11-08T11:41:46+03:00" level=fatal msg="exec failed with exit code 6"
The container does not know the name web. On Linux, nerdctl and Docker answer container names with their own DNS server, but nerdctl on Windows has nothing like that: the container asks the host's DNS server, which it got from the CNI plugin in the first part, and that server knows nothing about containers. The addresses are also new each time (the nat plugin hands them out from the subnet in no particular order), so writing them into the application in advance will not work either.
What nerdctl offers
On Linux, nerdctl, like Docker, has three flags for this: --ip sets the container's address, --dns its DNS server, and --add-host appends a name to its hosts file. Let's try them:
nerdctl run --rm --ip 172.30.0.50 mcr.microsoft.com/windows/nanoserver:ltsc2025 cmd /c ver
nerdctl run --rm --dns 172.30.0.1 mcr.microsoft.com/windows/nanoserver:ltsc2025 cmd /c ver
nerdctl run --rm --add-host "web:$webIp" mcr.microsoft.com/windows/nanoserver:ltsc2025 cmd /c ver
time="2026-11-08T11:41:48+03:00" level=fatal msg="failed to verify networking settings: the following networking arguments are not supported on Windows: [--ip-address]"
time="2026-11-08T11:41:48+03:00" level=fatal msg="failed to verify networking settings: the following networking arguments are not supported on Windows: [--dns-servers]"
time="2026-11-08T11:41:48+03:00" level=fatal msg="failed to verify networking settings: the following networking arguments are not supported on Windows: [--add-host]"
On Windows all three are rejected. So we will have to solve this ourselves.
While we are at it, a word about the container's own name. --name is the container's name for nerdctl; it is not passed inside, and nerdctl on Windows does not let you set the computer name:
nerdctl run --rm --name foo mcr.microsoft.com/windows/nanoserver:ltsc2025 cmd /c "hostname & echo %COMPUTERNAME%"
nerdctl run --rm --name foo --hostname foo mcr.microsoft.com/windows/nanoserver:ltsc2025 cmd /c hostname
nerdctl run --rm --name foo -e COMPUTERNAME=foo mcr.microsoft.com/windows/nanoserver:ltsc2025 cmd /c "hostname & echo %COMPUTERNAME%"
minwinpc
MINWINPC
time="2026-11-08T16:07:08+03:00" level=fatal msg="failed to verify networking settings: the following networking arguments are not supported on Windows: [--hostname]"
minwinpc
foo
All containers are called minwinpc. The -e switch changes only the environment variable: programs that read %COMPUTERNAME% will see foo, but the actual computer name stays the same. It can be set only by talking to HCS directly; that will come in the fifth part.
A shared hosts file
The file C:\Windows\System32\drivers\etc\hosts is the oldest way to map names to addresses: the Windows DNS client looks in it before asking a DNS server. --add-host would have appended a line to this file in the container. Since we do not have the flag, we will do the same ourselves: in the first part we found out that containerd can mount an individual host file into a container. We will create one hosts file on the host and mount it into all containers in place of their own.
Let's start over: remove both containers, create a file with one line and start web with the file mounted:
nerdctl rm -f web client
New-Item -ItemType Directory C:\lab\dns -Force | Out-Null
'127.0.0.1 localhost' | Set-Content C:\lab\dns\hosts -Encoding ascii
$m = '-v', 'C:\lab\dns\hosts:C:\Windows\System32\drivers\etc\hosts:ro'
nerdctl run -d --name web -p 8080:8080 @m mcr.microsoft.com/dotnet/samples:aspnetapp-nanoserver-ltsc2025
The address of web is now known. Let's append it to the file and start client with the same file:
"$(Get-ContainerIp web) web" | Add-Content C:\lab\dns\hosts -Encoding ascii
nerdctl run -d --name client @m mcr.microsoft.com/windows/nanoserver:ltsc2025 ping -t localhost
nerdctl exec client cmd /c "type C:\Windows\System32\drivers\etc\hosts & ping -n 1 web & curl.exe -sS -o NUL -w %{http_code} http://web:8080/"
127.0.0.1 localhost
172.30.151.129 web
Pinging web [172.30.151.129] with 32 bytes of data:
Reply from 172.30.151.129: bytes=32 time<1ms TTL=128
Ping statistics for 172.30.151.129:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms
200
It works: client sees the file from the host, ping web takes the address from it, and the web request by name got through.
A different start order
But we started the containers in a convenient order: first web, then the line in the file, then client. In real life the order can be anything: for example, a client starts before the service and immediately tries to connect to it. Let's repeat this in reverse order:
nerdctl rm -f web client
'127.0.0.1 localhost' | Set-Content C:\lab\dns\hosts -Encoding ascii
nerdctl run -d --name client @m mcr.microsoft.com/windows/nanoserver:ltsc2025 ping -t localhost
nerdctl exec client cmd /c "ping -n 1 -w 500 web"
Ping request could not find host web. Please check the name and try again.
time="2026-11-08T11:45:36+03:00" level=fatal msg="exec failed with exit code 1"
While web does not exist, the name is not found, as expected. Now we start web and append its address:
nerdctl run -d --name web -p 8080:8080 @m mcr.microsoft.com/dotnet/samples:aspnetapp-nanoserver-ltsc2025
"$(Get-ContainerIp web) web" | Add-Content C:\lab\dns\hosts -Encoding ascii
nerdctl exec client cmd /c "type C:\Windows\System32\drivers\etc\hosts & ping -n 1 -w 500 web"
127.0.0.1 localhost
172.30.247.246 web
Ping request could not find host web. Please check the name and try again.
time="2026-11-08T11:45:39+03:00" level=fatal msg="exec failed with exit code 1"
The line is in the file (type shows it), but the name is still not found. Maybe we need to wait? We will ask every few seconds:
$t0 = Get-Date
do {
Start-Sleep 5
$r = nerdctl exec client cmd /c "ping -n 1 -w 300 web" | Select-String 'Pinging web'
} until ($r -or ((Get-Date) - $t0).TotalSeconds -ge 180)
if ($r) { "resolved after $([int]((Get-Date) - $t0).TotalSeconds) s" } else { "not resolved after $([int]((Get-Date) - $t0).TotalSeconds) s" }
not resolved after 183 s
Three minutes and nothing. The reason is the container's DNS client: it remembers answers, including negative ones, and client remembers that the name web does not exist. Its memory can be cleared with the ipconfig /flushdns command:
nerdctl exec client cmd /c "ipconfig /flushdns"
nerdctl exec --user ContainerAdministrator client cmd /c "ipconfig /flushdns"
nerdctl exec client cmd /c "ping -n 1 web & curl.exe -sS -o NUL -w %{http_code} http://web:8080/"
The requested operation requires elevation.
time="2026-11-08T11:48:42+03:00" level=fatal msg="exec failed with exit code 1"
Windows IP Configuration
Successfully flushed the DNS Resolver Cache.
Pinging web [172.30.247.246] with 32 bytes of data:
Reply from 172.30.247.246: bytes=32 time<1ms TTL=128
Ping statistics for 172.30.247.246:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms
200
ContainerUser, which Nano Server processes run as by default, cannot flush the cache: that needs administrator rights. ContainerAdministrator can, and after the flush the name is found right away. To sum up this approach:
- addresses are known only after startup, and we have to write them into the file ourselves;
- if a container asked for a name before it appeared in the file, it will not see it until someone with administrator rights flushes its cache;
- names work only in containers that have the file mounted.
Let's start with the first point: let the network itself hand out addresses and write them to the file when a container is created.
How CNI assigns addresses
In the first part we saw that a CNI plugin is a program that the runtime starts with the ADD or DEL command. CNI has one more division inside it: the network plugin (nat in our case) builds the network and connects the container to it, while choosing the address can be left to a separate IPAM (IP Address Management) plugin. It is called the same way, with the same environment variables and JSON on standard input, and it responds with JSON containing the address. On Linux, host-local, dhcp and static work this way.
Can Microsoft's nat do this? Its source code (common/core/network.go) has the answer: if the ipam section sets type, the plugin calls the program with that name from the CNI plugin directory and takes the address from it. Let's check what such a plugin receives, using a small program that writes its environment and input to a log and always returns the same address. We will put it in C:\Program Files\containerd\cni\bin\ipam-debug.exe and write "ipam": {"type": "ipam-debug", ...} in the .conflist:
nerdctl run --rm --name iptest mcr.microsoft.com/windows/nanoserver:ltsc2025 cmd /c "ipconfig | findstr IPv4"
Get-Content C:\lab\ipam-debug.log
IPv4 Address. . . . . . . . . . . : 172.30.0.77
=== 2026-11-08T15:38:23+03:00
CNI_COMMAND=ADD
CNI_CONTAINERID=34df1ac874f57194bf5809f1f1b6228a15a46f273a18044086b0f1605f5ccf59
CNI_NETNS=e61a972e-9eee-4414-8ca9-3ac132888004
CNI_IFNAME=eth0
CNI_ARGS=IgnoreUnknown=1
CNI_PATH=C:\Program Files\containerd\cni\bin
stdin: {"cniVersion":"0.3.0","name":"nat","type":"NAT","ipam":{"type":"ipam-debug","subnet":"172.30.0.0/16","routes":[{"dst":"\u003cnil\u003e"}]},"dns":{},"optionalFlags":{"localRoutedPortMapping":false,"allowAclPortMapping":false,"forceBridgeGateway":false,"enableDualStack":false,"loopbackDSR":false,"gatewayFromAdditionalRoutes":false},"runtimeConfig":{"dns":{}},"additionalRoutes":null,"AdditionalArgs":null}
...
=== 2026-11-08T15:38:25+03:00
CNI_NETNS=e61a972e-9eee-4414-8ca9-3ac132888004
CNI_CONTAINERID=34df1ac874f57194bf5809f1f1b6228a15a46f273a18044086b0f1605f5ccf59
CNI_COMMAND=DEL
CNI_IFNAME=eth0
CNI_PATH=C:\Program Files\containerd\cni\bin
CNI_ARGS=IgnoreUnknown=1
...
Three conclusions:
- It works. The container got 172.30.0.77, the address our program returned, and when the container was removed a
DELarrived, on which the address can be released. - The container name is not in the call. nerdctl passes the ID (
CNI_CONTAINERID), the network compartment (CNI_NETNS) andCNI_ARGS=IgnoreUnknown=1, and that is all. But by the time ofADD, the container is already recorded in containerd and has anerdctl/namelabel with the name. It can be requested from containerd by ID:ctr containers info <id>. natrebuilds theipamsection its own way. Only the fieldsnatitself knows (type,subnet,routesand a few more) reach our program, and it drops everything else. Even the gateway got lost: in the.conflistit is written as"gateway", while in the standard CNI route structure the field is calledgw, hence"dst":"<nil>". So the IPAM plugin's own settings will have to be kept in a separate file.
Our own IPAM: name-ipam
The plugin's job:
- on
ADD, find out the container's name from containerd and give it the first free address from the range; - remember what was given to whom, and release the address on
DEL; - maintain that same
hostsfile we mount into containers; now the plugin writes its lines; - discard the entries of containers containerd no longer knows: after a host reboot no
DELwill arrive for them.
We will write it in C# and build it with Native AOT, which compiles to an ordinary executable that needs no installed .NET. For a CNI plugin this matters: it starts as a separate process on every ADD and DEL, and it does not need a runtime on the server. The project is name-ipam.csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AssemblyName>name-ipam</AssemblyName>
<PublishAot>true</PublishAot>
<InvariantGlobalization>true</InvariantGlobalization>
<JsonSerializerIsReflectionEnabledByDefault>false</JsonSerializerIsReflectionEnabledByDefault>
</PropertyGroup>
</Project>
PublishAot enables compilation to native code. With it, System.Text.Json cannot parse JSON through reflection, so the JSON types are described by a source generator, and JsonSerializerIsReflectionEnabledByDefault turns an accidental use of reflection into a build error rather than a plugin crash at the moment a container starts.
The full code is in Program.cs; here is the main part. The settings, the leases and the JSON context:
public sealed class IpamConfig
{
public string Subnet { get; set; } = "";
public string Gateway { get; set; } = "";
public string RangeStart { get; set; } = "";
public string RangeEnd { get; set; } = "";
public Dictionary<string, string> Addresses { get; set; } = new();
public string? DnsTask { get; set; }
}
public sealed class Lease
{
public string Name { get; set; } = "";
public string Ip { get; set; } = "";
}
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, WriteIndented = true)]
[JsonSerializable(typeof(IpamConfig))]
[JsonSerializable(typeof(NetConfig))]
[JsonSerializable(typeof(Dictionary<string, Lease>))]
internal partial class CamelCaseContext : JsonSerializerContext;
Addresses and DnsTask are empty for now; we will get to them below. Now the command handling. Two instances of the plugin can run at the same time (when several containers start at once), so the lease file is read and written under a lock:
using var _ = Lock(Path.Combine(dataDir, "lock"));
switch (command)
{
case "ADD":
Prune(leases, id);
if (!leases.TryGetValue(id, out var lease))
{
var name = ContainerName(id);
lease = new Lease { Name = name, Ip = Pick(config, name, leases) };
leases[id] = lease;
}
Save(statePath, hostsPath, leases, config);
EnsureTask(config.DnsTask);
PrintResult(net.CniVersion ?? "0.3.0", config, lease.Ip);
return 0;
case "DEL":
leases.Remove(id);
Save(statePath, hostsPath, leases, config);
return 0;
// ...
}
The lock is a file opened exclusively: the second instance waits until the first closes it, and if the first crashes, Windows closes the file itself, so the lock cannot get stuck:
static FileStream Lock(string path)
{
for (var i = 0; ; i++)
{
try
{
return new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException) when (i < 100)
{
Thread.Sleep(100);
}
}
}
The container name comes from the nerdctl/name label; containers started through ctr have no such label and get a name from the first 12 characters of the ID:
static string ContainerName(string id)
{
var output = Exec("ctr", "-n", "default", "containers", "info", id);
if (output != null)
{
var info = JsonSerializer.Deserialize(output, PascalCaseContext.Default.ContainerInfo);
if (info?.Labels?.TryGetValue("nerdctl/name", out var name) == true && name != "") return name;
}
return id.Length > 12 ? id[..12] : id;
}
Pick chooses the first free address from the rangeStart–rangeEnd range; we will look at it in full below, when we need it. Save writes the leases to nat.json and rebuilds hosts from them. The file is overwritten in place rather than replaced with a new one: that way the containers it is mounted into can see it. The response in CNI format is the address with the prefix length, the gateway and a default route. The plugin also returns errors in CNI format, as JSON with code and msg fields, and nerdctl shows msg to the user.
Build and installation
It is more convenient to build on a workstation: besides .NET SDK 10, Native AOT needs the linker from Visual Studio or Build Tools with the C++ component. The build finds it with the vswhere.exe utility, which may not be in PATH:
$env:Path += ";${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer"
dotnet publish -c Release -o out
Get-ChildItem out | Format-Table Name, Length
Name Length
---- ------
name-ipam.exe 2715648
name-ipam.pdb 13479936
2.7 MB, no dependencies. Only name-ipam.exe is needed on the server; it goes next to the other CNI plugins. In the .conflist, instead of addresses there remain the plugin type, the subnet and the route, from which nat will create the network if needed:
"ipam": {
"type": "name-ipam",
"subnet": "172.30.0.0/16",
"routes": [
{ "gateway": "172.30.0.1" }
]
}
The plugin's settings are in C:\ProgramData\name-ipam\config.json. For now they contain only the subnet, the gateway and the address range:
Copy-Item .\name-ipam.exe "$env:ProgramFiles\containerd\cni\bin\"
New-Item -ItemType Directory C:\ProgramData\name-ipam -Force | Out-Null
@'
{
"subnet": "172.30.0.0/16",
"gateway": "172.30.0.1",
"rangeStart": "172.30.1.1",
"rangeEnd": "172.30.1.254"
}
'@ | Set-Content C:\ProgramData\name-ipam\config.json -Encoding ascii
Copy-Item .\0-containerd-nat.conflist "$env:ProgramFiles\containerd\cni\conf\" -Force
'127.0.0.1 localhost' | Set-Content C:\ProgramData\name-ipam\hosts -Encoding ascii
The last line is important. The plugin creates the hosts file on the first ADD, but nerdctl will mount it into the container earlier. If the file does not exist yet, nerdctl creates an empty folder in its place, and the plugin fails with an access denied error:
time="2026-11-08T11:48:58+03:00" level=fatal msg="plugin type=\"nat\" failed (add): UnauthorizedAccess_IODenied_Path, C:\\ProgramData\\name-ipam\\hosts"
So we create the file in advance.
Verification
Now we mount the plugin's file into all containers:
$m = '-v', 'C:\ProgramData\name-ipam\hosts:C:\Windows\System32\drivers\etc\hosts:ro'
nerdctl run -d --name web -p 8080:8080 @m mcr.microsoft.com/dotnet/samples:aspnetapp-nanoserver-ltsc2025
nerdctl run -d --name client @m mcr.microsoft.com/windows/nanoserver:ltsc2025 ping -t localhost
Get-Content C:\ProgramData\name-ipam\nat.json
Get-Content C:\ProgramData\name-ipam\hosts
nerdctl exec client cmd /c "ping -n 1 web & curl.exe -sS -o NUL -w %{http_code} http://web:8080/"
{
"90689bb7d9aa6f71b36e5c044923f72c4f3959fa73540749ca28391524446df3": {
"name": "web",
"ip": "172.30.1.1"
},
"6f176a736843e52d0da64c1b64408930cd0fa7ac88a361862b7264ca74e53235": {
"name": "client",
"ip": "172.30.1.2"
}
}
# generated by name-ipam, do not edit
127.0.0.1 localhost
172.30.1.1 web
172.30.1.2 client
Pinging web [172.30.1.1] with 32 bytes of data:
Reply from 172.30.1.1: bytes=32 time<1ms TTL=128
Ping statistics for 172.30.1.1:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms
200
We no longer write anything by hand: the plugin handed out the addresses and also wrote them to hosts. Now the reverse order, the one that broke the shared file:
nerdctl rm -f web client
nerdctl run -d --name client @m mcr.microsoft.com/windows/nanoserver:ltsc2025 ping -t localhost
nerdctl exec client cmd /c "ping -n 1 -w 500 web"
nerdctl run -d --name web -p 8080:8080 @m mcr.microsoft.com/dotnet/samples:aspnetapp-nanoserver-ltsc2025
nerdctl exec client cmd /c "type C:\Windows\System32\drivers\etc\hosts & ping -n 1 -w 500 web"
Ping request could not find host web. Please check the name and try again.
time="2026-11-08T11:51:45+03:00" level=fatal msg="exec failed with exit code 1"
# generated by name-ipam, do not edit
127.0.0.1 localhost
172.30.1.1 client
172.30.1.2 web
Ping request could not find host web. Please check the name and try again.
time="2026-11-08T11:51:47+03:00" level=fatal msg="exec failed with exit code 1"
The same wait loop as above gives up after three minutes: not resolved after 183 s. The line with web appeared in the file as soon as it started, but client had already asked for that name, and its DNS client remembers the failure. The plugin has saved us the manual work, but the cache has not gone anywhere. Something else is noticeable too: addresses are handed out in start order, and this time web got 172.30.1.2 instead of 172.30.1.1. A container's address changes every time it is recreated.
Address reservations
Both drawbacks go away if the service's address is known in advance, before its container starts. This is how a DHCP reservation works: an administrator binds an address to a machine's MAC address, and the machine gets it every time it connects. In our case, the container name takes the place of the MAC address. If web always gets 172.30.0.10, the line 172.30.0.10 web can stay in hosts permanently, and then client, asking for the name before web starts, will get an address rather than a failure.
Reservations are set in the plugin's settings in the addresses field, config.json:
{
"subnet": "172.30.0.0/16",
"gateway": "172.30.0.1",
"rangeStart": "172.30.1.1",
"rangeEnd": "172.30.1.254",
"addresses": {
"web": "172.30.0.10",
"db": "172.30.0.11"
}
}
The reserved addresses are below the range so as not to overlap with it. Pick now looks at the reservations first, and hands out addresses from the range, skipping reserved ones:
static string Pick(IpamConfig config, string name, Dictionary<string, Lease> leases)
{
var used = leases.Values.ToDictionary(l => l.Ip, l => l.Name);
if (config.Addresses.TryGetValue(name, out var fixedIp))
{
if (used.TryGetValue(fixedIp, out var other))
throw new InvalidOperationException($"address {fixedIp} of {name} is used by {other}");
return fixedIp;
}
var reserved = config.Addresses.Values.ToHashSet();
uint start = ToUInt(config.RangeStart), end = ToUInt(config.RangeEnd);
for (var n = start; n <= end; n++)
{
var ip = ToIp(n);
if (!used.ContainsKey(ip) && !reserved.Contains(ip)) return ip;
}
throw new InvalidOperationException($"no free address in {config.RangeStart}-{config.RangeEnd}");
}
And Save writes all reserved names to hosts, whether their containers are running or not, plus the running containers without a reservation:
var names = new Dictionary<string, string>(config.Addresses);
foreach (var l in leases.Values) names.TryAdd(l.Name, l.Ip);
var hosts = new StringBuilder("# generated by name-ipam, do not edit\r\n127.0.0.1 localhost\r\n");
foreach (var line in names.Select(n => $"{n.Value,-15} {n.Key}").Order(StringComparer.Ordinal))
hosts.Append(line).Append("\r\n");
WriteFile(hostsPath, hosts.ToString());
We put the new settings in place and immediately test the hard order, with client first:
nerdctl rm -f web client
Copy-Item .\config.json C:\ProgramData\name-ipam\ -Force
nerdctl run -d --name client @m mcr.microsoft.com/windows/nanoserver:ltsc2025 ping -t localhost
Get-Content C:\ProgramData\name-ipam\hosts
nerdctl exec client cmd /c "ping -n 1 -w 500 web"
# generated by name-ipam, do not edit
127.0.0.1 localhost
172.30.0.10 web
172.30.0.11 db
172.30.1.1 client
Pinging web [172.30.0.10] with 32 bytes of data:
Request timed out.
Ping statistics for 172.30.0.10:
Packets: Sent = 1, Received = 0, Lost = 1 (100% loss),
time="2026-11-08T11:54:07+03:00" level=fatal msg="exec failed with exit code 1"
web is not running yet, but client already knows its address: ping went to 172.30.0.10 and got no reply, since there is nothing to answer yet. Let's start web:
nerdctl run -d --name web -p 8080:8080 @m mcr.microsoft.com/dotnet/samples:aspnetapp-nanoserver-ltsc2025
nerdctl exec client cmd /c "ping -n 1 web & curl.exe -sS -o NUL -w %{http_code} http://web:8080/"
Pinging web [172.30.0.10] with 32 bytes of data:
Reply from 172.30.0.10: bytes=32 time=324ms TTL=128
Ping statistics for 172.30.0.10:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 324ms, Maximum = 324ms, Average = 324ms
200
Immediately, with no waiting and no cache flush. There is no failure in the cache, and the address client remembered is correct. It will stay correct after web is recreated:
nerdctl rm -f web
nerdctl run -d --name web -p 8080:8080 @m mcr.microsoft.com/dotnet/samples:aspnetapp-nanoserver-ltsc2025
nerdctl exec web cmd /c "ipconfig | findstr IPv4"
nerdctl exec client curl.exe -sS -o NUL -w "%{http_code}`n" http://web:8080/
IPv4 Address. . . . . . . . . . . : 172.30.0.10
200
This is the same idea as a Service in Kubernetes: a service has a permanent name and a permanent address that exist regardless of whether its pods are running right now and how many times they have been recreated. The client does not care which instance answers; it always goes to the same address. But a Service can have several pods behind that address, and Kubernetes distributes connections among them. Our reservation cannot do that: the address is bound to one container with that name. nerdctl will not create a second container named web, and under another name, say web-2, it will get an ordinary address from the range, and the name web will not point to it. One service, one container.
What is still in the way
For services whose addresses we have reserved, the problem is solved. But not all containers are services. Let's start worker without a reservation, asking about it beforehand:
nerdctl exec client cmd /c "ping -n 1 -w 300 worker"
nerdctl run -d --name worker @m mcr.microsoft.com/windows/nanoserver:ltsc2025 ping -t localhost
Get-Content C:\ProgramData\name-ipam\hosts
Ping request could not find host worker. Please check the name and try again.
time="2026-11-08T11:54:14+03:00" level=fatal msg="exec failed with exit code 1"
# generated by name-ipam, do not edit
127.0.0.1 localhost
172.30.0.10 web
172.30.0.11 db
172.30.1.1 client
172.30.1.2 worker
The line appeared, but the wait loop again gives up after three minutes: not resolved after 183 s. For containers without a reservation, the cache still gets in the way. Second, all of this works only in containers that have our hosts mounted. A container started without -v does not know a single name:
nerdctl run --rm mcr.microsoft.com/windows/nanoserver:ltsc2025 cmd /c "ping -n 1 -w 300 web"
Ping request could not find host web. Please check the name and try again.
Both drawbacks follow from the fact that each container reads the file itself and decides itself how long to remember an answer. We need an intermediary that answers names on request and sets how long an answer lives in the cache: a DNS server.
CoreDNS
A DNS server is a service that answers queries of the form "what is the address of this name". If containers ask our server rather than reading the file themselves, both drawbacks disappear: no file needs to be mounted, and an answer lives in the container's cache as long as the server says. CoreDNS is a DNS server assembled from plugins (the same one that resolves service names in Kubernetes). It has a Windows build and a hosts plugin, which answers with names from a file in hosts format and notices changes to it by itself. We already have the file: name-ipam maintains it.
Where to listen
Containers need an address they can definitely reach: the gateway of the nat network, 172.30.0.1. There is no reason to listen on all host addresses: a DNS server for containers should not answer on the host's network. But the gateway address has a peculiarity: it appears only together with the nat network, and the HNS network created by the nat plugin does not survive a host reboot. After boot it is not there until the first container starts; we will see this below, during verification. While the address does not exist, CoreDNS with the bind 172.30.0.1 directive does not start:
& C:\coredns\coredns.exe -conf C:\coredns\Corefile
maxprocs: Leaving GOMAXPROCS=4: CPU quota undefined
Listen: listen tcp 172.30.0.1:53: bind: The requested address is not valid in its context.
Starting it with a task at Windows startup does not guarantee the result. In three experiments CoreDNS exited with code 1 once, and twice managed to take the port on 172.30.0.1, even though a minute and a half after boot neither the nat network nor that address was on the host any more. In the case I checked, such a CoreDNS began working when the first container recreated the network, but I did not find out why the outcome varies, and it cannot be relied on. The reliable moment to start it is when the network already exists, and that is the moment of our plugin's ADD: nat creates the network before it asks for an address. So name-ipam can start a scheduled task if it is not already running; the dnsTask field in its settings is for that:
static void EnsureTask(string? task)
{
if (string.IsNullOrEmpty(task)) return;
var state = Exec("schtasks", "/Query", "/TN", task, "/FO", "CSV", "/NH");
if (state != null && state.Contains("\"Running\"")) return;
Exec("schtasks", "/Run", "/TN", task);
}
Errors here deliberately do not abort ADD: a container without DNS is better than a container that has not started.
Installation
Everything is collected in install-coredns.ps1:
.\install-coredns.ps1
CoreDNS
coredns_1.15.0_windows_amd64.zip sha256 ok
Corefile
Firewall
Scheduled task
name-ipam config
nat network config
Step by step:
CoreDNS: the archive from GitHub into
C:\coredns, with a checksum verification.Corefile: the CoreDNS configuration:
. { bind 172.30.0.1 hosts C:\ProgramData\name-ipam\hosts { ttl 5 reload 1s fallthrough } forward . 192.168.10.1 errors }bindlistens only on the gateway address.hostsanswers names from the file maintained byname-ipam, rereads it every second (reload) and serves answers with a 5-second time to live (ttl): that is how long the container's DNS client will remember them.fallthroughpasses names that are not in the file to the next plugin,forward, which sends them on to the host's DNS server: that is how containers can still resolvemcr.microsoft.com.errorswrites errors to the log.Firewall: two rules, UDP and TCP on port 53 (DNS uses both), only to the address 172.30.0.1 and only from the container subnet.
Scheduled task
CoreDNS: runscoredns.exe -conf C:\coredns\Corefileas SYSTEM. It has no trigger:name-ipamstarts it. CoreDNS cannot run as a Windows service on its own, which is why it is a task and not a service.dnsTaskin thename-ipamsettings: the name of this task.DNS server in the
.conflist:"dns": {"nameservers": ["172.30.0.1"]}is added to thenatplugin, and new containers get this server instead of the host's DNS server.
There is no longer any need to mount hosts into containers: from here on all containers start without -v.
Verification
The client and worker containers are no longer needed. Let's remove them and reboot the host, leaving the web container created, to look at the whole chain from scratch:
nerdctl rm -f client worker
Restart-Computer
# after the reboot
Get-HnsNetwork
[bool](Get-Process coredns -ErrorAction SilentlyContinue)
nerdctl start web
False
time="2026-11-08T14:56:55+03:00" level=fatal msg="1 errors:\nfailed to create shim task: hcs::CreateComputeSystem 61ef4b0b5f255ce273d2ce1b02c39068495bd65cd40b9bb8d7df0e9bd310eb7b: Element not found."
Get-HnsNetwork printed nothing: after the reboot there is no nat network, and with it no gateway address and no endpoint of the old container, so web does not start. CoreDNS is not running. Let's remove the container and create it again; the plugin will create the nat network itself:
nerdctl rm -f web
nerdctl run -d --name web -p 8080:8080 mcr.microsoft.com/dotnet/samples:aspnetapp-nanoserver-ltsc2025
nerdctl run -d --name client mcr.microsoft.com/windows/nanoserver:ltsc2025 ping -t localhost
Get-NetUDPEndpoint -LocalPort 53 | Format-Table LocalAddress, OwningProcess
Get-NetTCPConnection -LocalPort 53 -State Listen | Format-Table LocalAddress, OwningProcess
LocalAddress OwningProcess
------------ -------------
172.30.0.1 5768
LocalAddress OwningProcess
------------ -------------
172.30.0.1 5768
CoreDNS started together with the first container and listens on port 53 only on the gateway address. From inside client:
nerdctl exec client cmd /c "ipconfig | findstr IPv4 & ipconfig /all | findstr Servers"
nerdctl exec client cmd /c "ping -n 1 web" | Select-String 'Pinging|Reply'
nerdctl exec client curl.exe -sS -o NUL -w "%{http_code}`n" http://web:8080/
nerdctl exec client curl.exe -sS -o NUL -w "%{http_code}`n" https://mcr.microsoft.com/v2/
IPv4 Address. . . . . . . . . . . : 172.30.1.1
DNS Servers . . . . . . . . . . . : 172.30.0.1
Pinging web [172.30.0.10] with 32 bytes of data:
Reply from 172.30.0.10: bytes=32 time<1ms TTL=128
200
200
The container's DNS server is CoreDNS, the name web resolves to the reserved address, external names work too, and all of this with no hosts mounted. Now for what neither the shared file nor the reservations could manage: a container without a reservation that client asked about in advance:
nerdctl exec client cmd /c "ping -n 1 -w 300 worker" | Select-String 'Pinging|could not find'
nerdctl run -d --name worker mcr.microsoft.com/windows/nanoserver:ltsc2025 ping -t localhost
Get-Content C:\ProgramData\name-ipam\hosts
nerdctl exec client cmd /c "ping -n 1 -w 300 worker" | Select-String 'Pinging|could not find'
Resolve-DnsName worker -Server 172.30.0.1 -DnsOnly | Format-Table Name, Type, TTL, IPAddress
nerdctl rm -f worker
$t0 = Get-Date
do { Start-Sleep 1; $r = nerdctl exec client cmd /c "ping -n 1 -w 300 worker" | Select-String 'could not find' } until ($r)
"gone after $([int]((Get-Date) - $t0).TotalSeconds) s"
Ping request could not find host worker. Please check the name and try again.
time="2026-11-08T14:57:02+03:00" level=fatal msg="exec failed with exit code 1"
71c9ac8141416722cda2ccf135d9746397763e29e2b0194519dfa4177bb0ab95
# generated by name-ipam, do not edit
127.0.0.1 localhost
172.30.0.10 web
172.30.0.11 db
172.30.1.1 client
172.30.1.2 worker
Pinging worker [172.30.1.2] with 32 bytes of data:
Name Type TTL IPAddress
---- ---- --- ---------
worker A 5 172.30.1.2
worker
time="2026-11-08T14:57:05+03:00" level=fatal msg="exec failed with exit code 1"
time="2026-11-08T14:57:07+03:00" level=fatal msg="exec failed with exit code 1"
time="2026-11-08T14:57:09+03:00" level=fatal msg="exec failed with exit code 1"
gone after 5 s
worker got the next address in the range, and client, which had just failed to find this name, found it right after the container started, with no cache flushes and no mounted files. CoreDNS serves the answer with a 5-second time to live, and a failure is also short-lived. After the container was removed, the name disappeared in 5 seconds, the answer's time to live from the Corefile.
Cleaning up
We no longer need the containers, images and working folder from this part:
nerdctl rm -f web client
nerdctl rmi mcr.microsoft.com/dotnet/samples:aspnetapp-nanoserver-ltsc2025 mcr.microsoft.com/windows/nanoserver:ltsc2025
Remove-Item C:\lab -Recurse -Force
The name-ipam plugin and the CoreDNS task stay on the server: in the next parts containers get their addresses and names through them.
The result
nerdctl run --name web
│
▼
nerdctl → CNI nat ── creates the nat network, gateway 172.30.0.1
│
▼ ADD
name-ipam ── name web from containerd
│ address 172.30.0.10 from the reservation
│ hosts, nat.json
│ schtasks /Run CoreDNS, if not running
▼
container: address 172.30.0.10, DNS 172.30.0.1
│
▼ name query
CoreDNS 172.30.0.1:53 ── hosts → container names
forward → host DNS server
We went through four steps, and each one removed one problem of the previous one:
- A shared
hostsmounted into containers. Works if containers start in a convenient order. Addresses have to be written in by hand, and a container that asked for a name too early will not see it until its cache is flushed. - Our own IPAM plugin,
name-ipam. Thenatplugin leaves the choice of address to an external program, and our program hands out addresses and maintainshostsitself. The manual work is gone, the cache remains. - Reservations. A service's address is known in advance, the line with it is in
hostsbefore the container starts, and the cache has nothing to spoil. Like a Service in Kubernetes, but with one container per name. - CoreDNS on the gateway address. Answers names on request with a short answer time to live, so it works both for containers without a reservation and without mounted files. It is started by the same
name-ipam, because the gateway address appears only together with the network.
In Kubernetes this is done by CoreDNS and the IPAM plugin of the networking solution: Calico, from part 37 of the Kubernetes series, has its own IPAM with blocks of addresses per node, and CoreDNS answers the names of services. Here we have built the same thing for one machine from two small programs.
Sources
- CNI specification — the CNI specification: plugins, IPAM delegation, the response and error format.
- microsoft/windows-container-networking — the source code of the
natplugin, including the call to an external IPAM. - Native AOT deployment — Microsoft Learn: Native AOT and its requirements.
- How to use source generation in System.Text.Json — Microsoft Learn: code generation for JSON.
- CoreDNS — the CoreDNS documentation, the hosts, bind and forward plugins.
- Service — the Kubernetes documentation: a permanent name and address for a group of pods.
Next — we will look inside a running container: where containerd stores image layers, how the container's disk is assembled from them, what sandbox.vhdx is, how the wcifs and bindflt filters merge the layers and mount host folders, and what a server silo looks like in the kernel object namespace.
Only registered users can leave a comment.
Sign in or register to leave a comment.