fix(docker): let the daemon pick dynamic host ports (#5928)

A dynamic port binding sent a port Floci picked with ServerSocket(0), probed
where Floci runs. On Docker Desktop the daemon binds it inside the VM, whose
ephemeral range lies inside the Mac's, so a VM socket on that number failed
the start with "address already in use" and CreateDBInstance returned 500.
The binding now leaves the host port empty and the endpoint is read back from
inspect, as before.
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-10-18 09:20:50 -04:00
1 parent e38dba5f11
commit 8972b21e1b
16 files changed
+72 -85

No files matched your search

@@ -90,7 +90,6 @@ public class ContainerLifecycleManager {
private final DockerClient dockerClient;
private final ImageCacheService imageCacheService;
private final ContainerDetector containerDetector;
private final PortAllocator portAllocator;
private final EmulatorConfig config;
/** Volumes whose shared-ownership root has already been initialised this process (run-once guard). */
@@ -103,12 +102,10 @@ public class ContainerLifecycleManager {
public ContainerLifecycleManager(DockerClient dockerClient,
ImageCacheService imageCacheService,
ContainerDetector containerDetector,
PortAllocator portAllocator,
EmulatorConfig config) {
this.dockerClient = dockerClient;
this.imageCacheService = imageCacheService;
this.containerDetector = containerDetector;
this.portAllocator = portAllocator;
this.config = config;
}
@@ -1272,14 +1269,9 @@ public class ContainerLifecycleManager {
for (Map.Entry<Integer, Integer> entry : spec.portBindings().entrySet()) {
int containerPort = entry.getKey();
int hostPort = entry.getValue();
// 0 means dynamic allocation
if (hostPort == 0) {
hostPort = portAllocator.allocateAny();
}
ports.bind(ExposedPort.tcp(containerPort), bindingFor(spec, containerPort, hostPort));
LOG.debugv("Port binding: {0} -> {1}", String.valueOf(containerPort), String.valueOf(hostPort));
LOG.debugv("Port binding: {0} -> {1}", String.valueOf(containerPort),
hostPort == 0 ? "dynamic" : String.valueOf(hostPort));
}
hostConfig.withPortBindings(ports);
} else if (spec.hasPortBindings()) {
@@ -1348,17 +1340,20 @@ public class ContainerLifecycleManager {
* form of the same decision, for a port that is an implementation detail and must never leave
* the host. A port in neither binds every interface, which is Docker's own default and what
* every caller that does not ask has always got.
*
* <p>A host port of 0 leaves the port to the daemon, and the endpoint is read back from
* inspect after start. A port Floci picked itself would be probed where Floci runs, not where
* the daemon binds it: on Docker Desktop that is the VM, whose ephemeral range lies inside the
* Mac's, so a VM socket on the same number fails the start with "address already in use".
*/
private static Ports.Binding bindingFor(ContainerSpec spec, int containerPort, int hostPort) {
String hostIp = spec.portBindingHostIps() == null
? null
: spec.portBindingHostIps().get(containerPort);
if (hostIp != null && !hostIp.isBlank()) {
return Ports.Binding.bindIpAndPort(hostIp, hostPort);
if (hostIp == null || hostIp.isBlank()) {
hostIp = spec.loopbackPortBindings().contains(containerPort) ? LOOPBACK_HOST_IP : null;
}
return spec.loopbackPortBindings().contains(containerPort)
? Ports.Binding.bindIpAndPort(LOOPBACK_HOST_IP, hostPort)
: Ports.Binding.bindPort(hostPort);
return new Ports.Binding(hostIp, hostPort == 0 ? null : String.valueOf(hostPort));
}
/**
@@ -18,9 +18,10 @@ import java.util.concurrent.ConcurrentSkipListSet;
import java.util.function.IntFunction;
/**
* Utility for allocating free TCP ports for Docker container port bindings.
* Consolidates the free port discovery logic previously duplicated across
* container managers (RDS, ElastiCache, MSK, ECR).
* Allocates host ports from a configured range for callers that must know the port before
* the container starts, or that hand it out themselves (ECR, EC2, MSK and other range-based
* managers). A binding that only needs some free port uses a dynamic port instead
* ({@code ContainerBuilder.Builder#withDynamicPort}), which leaves the choice to the daemon.
*/
@ApplicationScoped
public class PortAllocator {
@@ -142,24 +143,6 @@ public class PortAllocator {
return false;
}
/**
* Finds any free TCP port using ephemeral port allocation.
* This is the fastest method when any port will do.
*
* @return a free port
* @throws RuntimeException if no free port can be allocated
*/
public int allocateAny() {
try (ServerSocket socket = new ServerSocket(0)) {
socket.setReuseAddress(true);
int port = socket.getLocalPort();
LOG.debugv("Allocated ephemeral port {0}", String.valueOf(port));
return port;
} catch (IOException e) {
throw new RuntimeException("Could not find a free port", e);
}
}
/**
* Checks if a specific port is currently free.
*
@@ -53,7 +53,6 @@ class ContainerLifecycleManagerCaBundleTest {
@Mock DockerClient dockerClient;
@Mock ImageCacheService imageCacheService;
@Mock ContainerDetector containerDetector;
@Mock PortAllocator portAllocator;
@Mock EmulatorConfig config;
@Mock EmulatorConfig.DockerConfig dockerConfig;
@Mock EmulatorConfig.TlsConfig tlsConfig;
@@ -205,7 +204,6 @@ class ContainerLifecycleManagerCaBundleTest {
assertEquals(6, env.getAllValues().get(0).size(), "the first attempt carried the trust variables");
assertEquals(List.of("FOO=bar"), env.getAllValues().get(1), "the retry carries only the spec's own");
verify(dockerClient, times(1)).copyArchiveToContainerCmd(anyString());
verify(portAllocator, never()).allocateAny();
}
private Path writeBundle() throws Exception {
@@ -214,7 +212,7 @@ class ContainerLifecycleManagerCaBundleTest {
}
private ContainerLifecycleManager manager() {
return new ContainerLifecycleManager(dockerClient, imageCacheService, containerDetector, portAllocator, config);
return new ContainerLifecycleManager(dockerClient, imageCacheService, containerDetector, config);
}
private static ContainerSpec specWithEnv(List<String> env) {
@@ -139,7 +139,7 @@ class ContainerLifecycleManagerCpuLimitTest {
ImageCacheService imageCacheService = mock(ImageCacheService.class);
when(imageCacheService.ensureImageExists(any())).thenAnswer(invocation -> invocation.getArgument(0));
ContainerLifecycleManager manager = new ContainerLifecycleManager(
dockerClient, imageCacheService, mock(ContainerDetector.class), mock(PortAllocator.class), config);
dockerClient, imageCacheService, mock(ContainerDetector.class), config);
manager.create(spec);
@@ -45,9 +45,6 @@ class ContainerLifecycleManagerCreateConflictRecoveryTest {
@Mock
ContainerDetector containerDetector;
@Mock
PortAllocator portAllocator;
@Mock
EmulatorConfig config;
@@ -221,6 +218,6 @@ class ContainerLifecycleManagerCreateConflictRecoveryTest {
private ContainerLifecycleManager manager() {
return new ContainerLifecycleManager(
dockerClient, imageCacheService, containerDetector, portAllocator, config);
dockerClient, imageCacheService, containerDetector, config);
}
}
@@ -48,9 +48,6 @@ class ContainerLifecycleManagerDeviceRequestTest {
@Mock
ContainerDetector containerDetector;
@Mock
PortAllocator portAllocator;
@Mock
EmulatorConfig config;
@@ -109,7 +106,7 @@ class ContainerLifecycleManagerDeviceRequestTest {
private ContainerLifecycleManager manager() {
return new ContainerLifecycleManager(
dockerClient, imageCacheService, containerDetector, portAllocator, config);
dockerClient, imageCacheService, containerDetector, config);
}
private static ContainerSpec specWithDeviceRequests(List<DeviceRequest> deviceRequests) {
@@ -39,15 +39,11 @@ class ContainerLifecycleManagerImageLabelsTest {
@Mock
ContainerDetector containerDetector;
@Mock
PortAllocator portAllocator;
@Mock
EmulatorConfig config;
private ContainerLifecycleManager manager() {
return new ContainerLifecycleManager(dockerClient, imageCacheService, containerDetector,
portAllocator, config);
return new ContainerLifecycleManager(dockerClient, imageCacheService, containerDetector, config);
}
private void imageInspectReturns(Map<String, String> labels) {
@@ -59,9 +59,6 @@ class ContainerLifecycleManagerLabelsTest {
@Mock
ContainerDetector containerDetector;
@Mock
PortAllocator portAllocator;
@Mock
EmulatorConfig config;
@@ -292,7 +289,7 @@ class ContainerLifecycleManagerLabelsTest {
private ContainerLifecycleManager manager() {
return new ContainerLifecycleManager(
dockerClient, imageCacheService, containerDetector, portAllocator, config);
dockerClient, imageCacheService, containerDetector, config);
}
private static ContainerSpec specWithLabels(Map<String, String> labels) {
@@ -33,9 +33,6 @@ class ContainerLifecycleManagerLivenessTest {
@Mock
private ContainerDetector containerDetector;
@Mock
private PortAllocator portAllocator;
@Mock
private EmulatorConfig config;
@@ -47,7 +44,7 @@ class ContainerLifecycleManagerLivenessTest {
@BeforeEach
void setUp() {
manager = new ContainerLifecycleManager(
dockerClient, imageCacheService, containerDetector, portAllocator, config);
dockerClient, imageCacheService, containerDetector, config);
when(dockerClient.inspectContainerCmd("c1")).thenReturn(inspectCmd);
}
@@ -12,6 +12,7 @@ import com.github.dockerjava.api.command.RemoveContainerCmd;
import com.github.dockerjava.api.command.StartContainerCmd;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.ContainerNetwork;
import com.github.dockerjava.api.model.ExposedPort;
import com.github.dockerjava.api.model.HostConfig;
import com.github.dockerjava.api.model.NetworkSettings;
import com.github.dockerjava.api.model.Ports;
@@ -63,9 +64,6 @@ class ContainerLifecycleManagerNetworkTest {
@Mock
ContainerDetector containerDetector;
@Mock
PortAllocator portAllocator;
@Mock
EmulatorConfig config;
@@ -208,10 +206,24 @@ class ContainerLifecycleManagerNetworkTest {
}
@Test
void createDoesNotAllocateDynamicPortsOnHostNetwork() {
void createPublishesNoDynamicPortOnHostNetwork() {
manager().create(spec("host", Map.of(9200, 0), List.of()));
verify(portAllocator, never()).allocateAny();
assertNull(createdHostConfig().getPortBindings());
}
@Test
void createAndStartReadsTheDaemonsDynamicPortBackFromInspect() {
when(dockerClient.startContainerCmd("container-id")).thenReturn(mock(StartContainerCmd.class));
Ports published = new Ports();
published.bind(ExposedPort.tcp(5432), Ports.Binding.bindPort(55037));
NetworkSettings networks = mock(NetworkSettings.class);
when(networks.getPorts()).thenReturn(published);
when(inspectOf("container-id").getNetworkSettings()).thenReturn(networks);
ContainerInfo info = manager().createAndStart(spec(null, Map.of(5432, 0), List.of(5432)));
assertEquals(new EndpointInfo("localhost", 55037), info.getEndpoint(5432));
}
@Test
@@ -366,8 +378,7 @@ class ContainerLifecycleManagerNetworkTest {
}
private ContainerLifecycleManager manager() {
return new ContainerLifecycleManager(dockerClient, imageCacheService, containerDetector,
portAllocator, config);
return new ContainerLifecycleManager(dockerClient, imageCacheService, containerDetector, config);
}
private static ContainerSpec spec(String networkMode, Map<Integer, Integer> portBindings,
@@ -73,6 +73,32 @@ class ContainerLifecycleManagerPortBindingTest {
assertNull(binding.getHostIp());
}
@Test
void aDynamicPortLeavesTheHostPortToTheDaemon() {
Ports.Binding binding = bindingFor(builder -> builder.withDynamicPort(5432), 5432);
assertNull(binding.getHostIp());
assertNull(binding.getHostPortSpec(), "Floci must not pick a port the daemon cannot see");
}
@Test
void aDynamicLoopbackPortStaysOnLoopback() {
Ports.Binding binding = bindingFor(
builder -> builder.withLoopbackPortBinding(5050, 0), 5050);
assertEquals("127.0.0.1", binding.getHostIp());
assertNull(binding.getHostPortSpec());
}
@Test
void aDynamicPortKeepsAnExplicitHostIp() {
Ports.Binding binding = bindingFor(
builder -> builder.withPortBinding(4500, 0, "127.0.0.1"), 4500);
assertEquals("127.0.0.1", binding.getHostIp());
assertNull(binding.getHostPortSpec());
}
@Test
void oneBoundInterfaceDoesNotLeakOntoTheOtherPorts() {
ContainerSpec spec = specFor(builder -> builder
@@ -114,9 +140,8 @@ class ContainerLifecycleManagerPortBindingTest {
when(createCmd.exec()).thenReturn(response);
ImageCacheService imageCacheService = mock(ImageCacheService.class);
when(imageCacheService.ensureImageExists(any())).thenAnswer(invocation -> invocation.getArgument(0));
PortAllocator portAllocator = mock(PortAllocator.class);
ContainerLifecycleManager manager = new ContainerLifecycleManager(
dockerClient, imageCacheService, mock(ContainerDetector.class), portAllocator, config);
dockerClient, imageCacheService, mock(ContainerDetector.class), config);
manager.create(spec);
@@ -44,9 +44,6 @@ class ContainerLifecycleManagerStartFailureTest {
@Mock
private ContainerDetector containerDetector;
@Mock
private PortAllocator portAllocator;
@Mock
private EmulatorConfig config;
@@ -56,7 +53,7 @@ class ContainerLifecycleManagerStartFailureTest {
@BeforeEach
void setUp() {
manager = spy(new ContainerLifecycleManager(
dockerClient, imageCacheService, containerDetector, portAllocator, config));
dockerClient, imageCacheService, containerDetector, config));
}
@Test
@@ -52,9 +52,6 @@ class ContainerLifecycleManagerStartTest {
@Mock
private ContainerDetector containerDetector;
@Mock
private PortAllocator portAllocator;
@Mock
private EmulatorConfig config;
@@ -77,7 +74,7 @@ class ContainerLifecycleManagerStartTest {
private ContainerLifecycleManager manager(DockerClient docker) {
return new ContainerLifecycleManager(
docker, imageCacheService, containerDetector, portAllocator, config);
docker, imageCacheService, containerDetector, config);
}
@Test
@@ -31,7 +31,7 @@ class ContainerLifecycleManagerTeardownTest {
@Test
void interruptedWaitersStillCleanUpWithoutReleasingAnotherOwnersSlot() throws Exception {
DockerClient docker = mock(DockerClient.class);
ContainerLifecycleManager manager = new ContainerLifecycleManager(docker, null, null, null, null);
ContainerLifecycleManager manager = new ContainerLifecycleManager(docker, null, null, null);
StopContainerCmd stop = mock(StopContainerCmd.class);
when(docker.stopContainerCmd(anyString())).thenReturn(stop);
when(stop.withTimeout(anyInt())).thenReturn(stop);
@@ -120,7 +120,7 @@ class ContainerLifecycleManagerTeardownTest {
@Test
void removalFailuresReleaseAdmissionForLaterOwners() throws Exception {
DockerClient docker = mock(DockerClient.class);
ContainerLifecycleManager manager = new ContainerLifecycleManager(docker, null, null, null, null);
ContainerLifecycleManager manager = new ContainerLifecycleManager(docker, null, null, null);
StopContainerCmd stop = mock(StopContainerCmd.class);
when(docker.stopContainerCmd(anyString())).thenReturn(stop);
when(stop.withTimeout(anyInt())).thenReturn(stop);
@@ -55,9 +55,6 @@ class ContainerLifecycleManagerVolumeTest {
@Mock
private ContainerDetector containerDetector;
@Mock
private PortAllocator portAllocator;
@Mock
private EmulatorConfig config;
@@ -66,7 +63,7 @@ class ContainerLifecycleManagerVolumeTest {
@BeforeEach
void setUp() {
manager = new ContainerLifecycleManager(
dockerClient, imageCacheService, containerDetector, portAllocator, config);
dockerClient, imageCacheService, containerDetector, config);
}
@Test
@@ -75,7 +75,7 @@ class ContainerLifecycleManagerVolumesFromTest {
ImageCacheService imageCacheService = mock(ImageCacheService.class);
when(imageCacheService.ensureImageExists(any())).thenAnswer(invocation -> invocation.getArgument(0));
ContainerLifecycleManager manager = new ContainerLifecycleManager(
dockerClient, imageCacheService, mock(ContainerDetector.class), mock(PortAllocator.class), config);
dockerClient, imageCacheService, mock(ContainerDetector.class), config);
manager.create(spec);