Skip to content

Add sticky container IPs across stop/start - #1740

Open
vsarunas wants to merge 7 commits into
apple:mainfrom
ordo-one:sticky-container-ip
Open

vsarunas wants to merge 7 commits into
apple:mainfrom
ordo-one:sticky-container-ip

Conversation

@vsarunas

Copy link
Copy Markdown

Type of Change

  • Bug fix
  • New feature
  • Breaking change
  • Documentation update

Motivation and Context

Currently upon a container stop/start, the IP address will always be incremented, even if there is free IP addresses available. This can sometimes cause issues with other software running inside the container where the IPs are always changing and require reconfiguration/handling.

The PR adds simple best attempt to restore the previous IP addresses allocated if the network still has available IPs, essentially giving static IPs under normal use. Upon network IP exhaustion, a starting container takes an IP from a stopped container.

Sticky

container run -d --name stick alpine sleep infinity

Will show the same IP persisted:

container list
ID     IMAGE                            OS     ARCH   STATE    IP               CPUS  MEMORY   STARTED
stick  docker.io/library/alpine:latest  linux  arm64  running  192.168.64.3/24  4     1024 MB  2026-06-17T11:24:31Z

container stop stick && container start stick

container list
ID     IMAGE                            OS     ARCH   STATE    IP               CPUS  MEMORY   STARTED
stick  docker.io/library/alpine:latest  linux  arm64  running  192.168.64.3/24  4     1024 MB  2026-06-17T11:24:51Z

Same can be done with start order, IP will be preserved:

for n in s1 s2 s3; do container run -d --name $n alpine sleep infinity; done
for n in s1 s2 s3; do container stop $n; done
for n in s3 s1 s2; do container start $n; done

Pool exhaustion and re-claim

Add a small network:

container network create --subnet 192.168.210.0/29 tiny

4 containers will be created:

for i in 1 2 3 4 5 6 7; do
  container run -d --name t$i --network tiny -m 256m alpine sleep infinity
done

Cannot allocate more once exhausted:

Error: failed to bootstrap container (cause: "internalError: "failed to bootstrap container t5 (cause: "invalidState: "network tiny (192.168.210.0/29) has no free IP addresses"")"")

The IP can be re-allocated from a stopped container on exhaustion and a new container can be now started:

container stop t1
container run -d --name t5 --network tiny -m 256m alpine sleep infinity

Testing

  • Tested locally
  • Added/updated tests
  • Added/updated docs

@vsarunas

Copy link
Copy Markdown
Author

@jglogan, could you have a look?

I originally started with a mix of this and static allocation similar to #751, but this has various edge cases on verifying the IP requested against stopped and running containers, but this gives majority of the benefit.

@vsarunas

Copy link
Copy Markdown
Author

@jglogan - what do you think ?

@florescercadojulio

Copy link
Copy Markdown

Since this is a best-effort strategy, would it make sense to notify the user when the previous IP cannot be reused and a new one has been assigned? Otherwise, users may assume the IP is stable and inadvertently build a fragile setup around that assumption.

Also, is there a common workflow in this project where users are expected to rely on container IPs instead of service discovery? If DNS-based service discovery is the recommended approach, I’m curious what use cases motivated adding sticky IP behavior.

@vsarunas

Copy link
Copy Markdown
Author

There is a debug log of when the IP address changes, I can change it from debug to a warning level.

There are certain places that you need to use an IP address only instead of DNS name (Kafka broker IP addresses list for example).

Yes, using DNS as well, it hasn't been without problems it self and sometimes have to flush cache straight after creation/restart:

sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder

@vsarunas

Copy link
Copy Markdown
Author

MAC address is now also preserved.

@vsarunas

Copy link
Copy Markdown
Author

@jglogan could you have a look at this PR please?

@vsarunas

Copy link
Copy Markdown
Author

@JaewonHur / @realrajaryan / @katiewasnothere , could you have a look at this PR please ?

# Conflicts:
#	Sources/ContainerCommands/Builder/BuilderStart.swift
#	Sources/ContainerResource/Network/AttachmentConfiguration.swift
#	Sources/Services/Network/Client/NetworkClient.swift
#	Sources/Services/Network/Server/AttachmentAllocator.swift
#	Sources/Services/Network/Server/DefaultNetworkService.swift
#	Sources/Services/Network/Server/NetworkHarness.swift
#	Sources/Services/Network/Server/NetworkService.swift
#	Sources/Services/RuntimeLinux/Server/RuntimeService.swift
#	Tests/ContainerNetworkServerTests/AttachmentAllocatorTest.swift
@vsarunas
vsarunas force-pushed the sticky-container-ip branch from d885913 to f57ed88 Compare October 20, 2026 12:08
@vsarunas

Copy link
Copy Markdown
Author

@jglogan could you have a look at this PR please?

@vsarunas

vsarunas commented Nov 2, 2026

Copy link
Copy Markdown
Author

@jglogan / @JaewonHur / @realrajaryan / @katiewasnothere - what do you think about this?

@SVilgelm

Copy link
Copy Markdown

Tested on an M5 Max (macOS 27.2.1), release build of main + this PR (+ #2485, #2378). IPs held across 5 stop/start cycles and across system stop/start, with and without a pinned MAC; 1.7.1 changed them every time. One gap: a stopped container doesn't reserve its address. After system start, a new container got s1's .2, then s1 took s2's .3 and s2 moved to .4, and those moves stayed.

@SVilgelm

Copy link
Copy Markdown

Follow-up to my test above, with a suggestion for the gap.

Gap: a stopped container's address goes back to the pool. releaseSession frees it when the runtime disconnects, and after system stop/start the network helper starts with an empty allocator. A new container can then take a stopped container's address, and acquireIndex's fallback can take another stopped container's address, so one collision cascades and the shifted addresses are written back to config.json. That's what I saw: a new container got s1's .2, s1 took s2's .3, and s2 moved to .4.

Suggestion: hold the address of a container that exists but isn't running, and free it on delete.

  1. AttachmentAllocator keeps holds reserved in the pool, so fresh allocations skip them and the owner gets its address back. When only held addresses are left, one is given up and its container is reassigned on its next start, the PR's existing best-effort path.
  2. releaseSession holds instead of freeing.
  3. Two network routes, hold(hostname, address) and release(hostname). NetworksService.init holds the recorded ipv4Address of each existing container right after starting its network (containers are loaded at boot before networks start), and container delete calls release.

I prototyped 1 and 2 on 0b1a43b; AttachmentAllocatorTest passes with four new tests. 3 is untested.

Diff for 1 and 2
diff --git a/Sources/Services/Network/Server/AttachmentAllocator.swift b/Sources/Services/Network/Server/AttachmentAllocator.swift
--- a/Sources/Services/Network/Server/AttachmentAllocator.swift
+++ b/Sources/Services/Network/Server/AttachmentAllocator.swift
@@ -47,6 +47,9 @@ actor AttachmentAllocator {
     private var subtreeAliases: [DNSName: String] = [:]
     // The aliases registered for each canonical hostname, so that they can be removed with it.
     private var aliasesByHostname: [String: [DNSMatchRule]] = [:]
+    // Addresses kept for stopped containers, by canonical hostname. They stay reserved in
+    // `allocator`, so fresh allocations skip them until the pool runs out.
+    private var held: [String: UInt32] = [:]
 
     init(lower: UInt32, size: Int) throws {
         allocator = try UInt32.rotatingAllocator(
@@ -101,6 +104,9 @@ actor AttachmentAllocator {
         let index: UInt32
         if let existing = hostnames[hostname] {
             index = existing
+        } else if let kept = held.removeValue(forKey: hostname) {
+            index = kept
+            hostnames[hostname] = index
         } else {
             index = try acquireIndex(requested: requested)
             hostnames[hostname] = index
@@ -121,20 +127,51 @@ actor AttachmentAllocator {
 
     private func acquireIndex(requested: UInt32?) throws -> UInt32 {
         guard let requested else {
-            return try allocator.allocate()
+            return try freshIndex()
         }
         do {
             try allocator.reserve(requested)
             return requested
         } catch AllocatorError.alreadyAllocated, AllocatorError.invalidAddress {
             // Address taken, or out of range after a subnet change - reassign.
+            return try freshIndex()
+        }
+    }
+
+    private func freshIndex() throws -> UInt32 {
+        do {
             return try allocator.allocate()
+        } catch AllocatorError.allocatorFull {
+            // Only held addresses are left: take one; its container is reassigned on its next start.
+            guard let (owner, index) = held.first else {
+                throw AllocatorError.allocatorFull
+            }
+            held.removeValue(forKey: owner)
+            return index
+        }
+    }
+
+    /// Keeps `index` for `hostname` while its container is stopped, so other allocations skip it.
+    func hold(hostname: String, index: UInt32) throws {
+        let hostname = AttachmentOptions.canonicalHostname(hostname)
+        guard hostnames[hostname] == nil, held[hostname] == nil else {
+            return
+        }
+        try allocator.reserve(index)
+        held[hostname] = index
+    }
+
+    /// Frees the address held for `hostname`, once its container is deleted.
+    func releaseHold(hostname: String) throws {
+        if let index = held.removeValue(forKey: AttachmentOptions.canonicalHostname(hostname)) {
+            try allocator.release(index)
         }
     }
 
     /// Free an allocated network address by hostname, along with the aliases registered for it.
+    /// With `hold`, the address stays reserved for the hostname (see `hold(hostname:index:)`).
     @discardableResult
-    func deallocate(hostname: String) async throws -> UInt32? {
+    func deallocate(hostname: String, hold: Bool = false) async throws -> UInt32? {
         let hostname = AttachmentOptions.canonicalHostname(hostname)
         guard let index = hostnames.removeValue(forKey: hostname) else {
             return nil
@@ -149,7 +186,11 @@ actor AttachmentAllocator {
             }
         }
 
-        try allocator.release(index)
+        if hold {
+            held[hostname] = index
+        } else {
+            try allocator.release(index)
+        }
         return index
     }
 
diff --git a/Sources/Services/Network/Server/DefaultNetworkService.swift b/Sources/Services/Network/Server/DefaultNetworkService.swift
--- a/Sources/Services/Network/Server/DefaultNetworkService.swift
+++ b/Sources/Services/Network/Server/DefaultNetworkService.swift
@@ -133,7 +133,8 @@ public actor DefaultNetworkService: NetworkService {
             return
         }
         for allocation in allocations {
-            _ = try? await allocator.deallocate(hostname: allocation.hostname)
+            // The container may start again: keep its address until it's deleted.
+            _ = try? await allocator.deallocate(hostname: allocation.hostname, hold: true)
             macAddresses.removeValue(forKey: allocation.index)
         }
         log.info("released session", metadata: ["allocations": "\(allocations.count)"])
Tests
diff --git a/Tests/ContainerNetworkServerTests/AttachmentAllocatorTest.swift b/Tests/ContainerNetworkServerTests/AttachmentAllocatorTest.swift
--- a/Tests/ContainerNetworkServerTests/AttachmentAllocatorTest.swift
+++ b/Tests/ContainerNetworkServerTests/AttachmentAllocatorTest.swift
@@ -158,6 +158,47 @@ struct AttachmentAllocatorTest {
         #expect(secondDeallocate == nil)
     }
 
+    @Test func testHeldAddressIsSkippedAndReturnedToItsOwner() async throws {
+        let allocator = try AttachmentAllocator(lower: 100, size: 3)  // pool [100, 103)
+        try await allocator.hold(hostname: "s1", index: 100)
+        try await allocator.hold(hostname: "s2", index: 101)
+
+        // A new container doesn't take a stopped container's address.
+        #expect(try await allocator.allocate(hostname: "new") == 102)
+        // The stopped containers get theirs back, in any order.
+        #expect(try await allocator.allocate(hostname: "s2", requested: 101) == 101)
+        #expect(try await allocator.allocate(hostname: "s1", requested: 100) == 100)
+    }
+
+    @Test func testStoppedContainerKeepsItsAddress() async throws {
+        let allocator = try AttachmentAllocator(lower: 100, size: 3)
+        let s1 = try await allocator.allocate(hostname: "s1")
+        try await allocator.deallocate(hostname: "s1", hold: true)
+
+        #expect(try await allocator.allocate(hostname: "new") != s1)
+        #expect(try await allocator.lookup(hostname: "s1") == nil)
+        #expect(try await allocator.allocate(hostname: "s1", requested: s1) == s1)
+    }
+
+    @Test func testHeldAddressIsGivenUpWhenThePoolIsFull() async throws {
+        let allocator = try AttachmentAllocator(lower: 100, size: 2)  // pool [100, 102)
+        try await allocator.hold(hostname: "s1", index: 100)
+        _ = try await allocator.allocate(hostname: "a")  // 101
+
+        #expect(try await allocator.allocate(hostname: "b") == 100)
+        // s1 is reassigned on its next start; here nothing is left.
+        await #expect(throws: AllocatorError.allocatorFull) {
+            try await allocator.allocate(hostname: "s1", requested: 100)
+        }
+    }
+
+    @Test func testReleasedHoldIsFree() async throws {
+        let allocator = try AttachmentAllocator(lower: 100, size: 1)
+        try await allocator.hold(hostname: "s1", index: 100)
+        try await allocator.releaseHold(hostname: "s1")
+        #expect(try await allocator.allocate(hostname: "a") == 100)
+    }
+
     @Test func testRequestedAddressIsReserved() async throws {
         let allocator = try AttachmentAllocator(lower: 100, size: 10)
         let address: UInt32 = 105  // any address within [100, 110)

reviewed by Claude (Opus 5.5)

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants