fix(docker): create a publishing container on its network off Docker Desktop (#7757)

* fix(docker): create a publishing container on its network off Docker Desktop

A container that publishes a host port was created on the default bridge
and connected to its configured network after it started, a workaround
for Docker Desktop, so on any other daemon it stayed on both. Off Docker
Desktop it is now created on its network and joins it alone; Docker
Desktop, and a daemon that cannot be asked, keep the connect after start.

* fix(docker): keep the daemon answer when it cannot be asked, so create and start agree

A failed GET /info fell back to the Docker Desktop path without keeping
that answer. If the daemon answered as Docker Engine by the time the
container started, it was created on the default bridge and never
connected to its network. The first answer, the fallback included, is
now kept.
This commit is contained in:
Niels Kootstra authored and GitHub committed 2026-11-08 05:22:36 -04:00
1 parent 767f50e13f
commit a3a3efec32
4 files changed
+133 -17

No files matched your search

@@ -101,6 +101,9 @@ public class ContainerLifecycleManager {
/** Daemon CPU count, resolved on first use. Null until then, so that empty can mean "unknown". */
private final AtomicReference<OptionalInt> hostCpuCount = new AtomicReference<>();
/** Whether the daemon is Docker Desktop, resolved on first use and kept. Null until then. */
private final AtomicReference<Boolean> dockerDesktop = new AtomicReference<>();
@Inject
public ContainerLifecycleManager(DockerClient dockerClient,
ImageCacheService imageCacheService,
@@ -362,7 +365,7 @@ public class ContainerLifecycleManager {
* network-connect endpoint, so the container is reconnected before it starts.
*/
private void attachNetworkBeforeStart(String containerId, ContainerSpec spec) {
if (!spec.hasPortBindings()) {
if (!connectsAfterStart(spec)) {
dockerClient.disconnectFromNetworkCmd()
.withContainerId(containerId)
.withNetworkId(spec.networkMode())
@@ -483,7 +486,7 @@ public class ContainerLifecycleManager {
LOG.infov("Started container {0}", containerId);
if (spec.networkMode() != null && !spec.networkMode().isBlank()
&& spec.publishesPorts() && !spec.hasNetworkConfiguration()) {
&& connectsAfterStart(spec) && !spec.hasNetworkConfiguration()) {
try {
dockerClient.connectToNetworkCmd()
.withContainerId(containerId)
@@ -1646,12 +1649,10 @@ public class ContainerLifecycleManager {
spec.name(), spec.networkMode(), spec.portBindings().keySet());
}
// Network mode: only set during creation when no host ports are published.
// withNetworkMode() + port bindings suppresses port publishing on macOS Docker Desktop,
// so containers with published ports (e.g. ECR registry) connect to the network
// after start via connectToNetworkCmd() instead. host, none and container:<id> publish
// nothing and cannot be connected after creation, so they always go on the HostConfig.
if (spec.networkMode() != null && !spec.networkMode().isBlank() && !spec.publishesPorts()) {
// Network mode: set during creation unless the container connects after start (see
// connectsAfterStart). host, none and container:<id> publish nothing and cannot be
// connected after creation, so they always go on the HostConfig.
if (spec.networkMode() != null && !spec.networkMode().isBlank() && !connectsAfterStart(spec)) {
hostConfig.withNetworkMode(spec.networkMode());
}
@@ -1763,6 +1764,27 @@ public class ContainerLifecycleManager {
return resolved;
}
/**
* Whether a container joins its network only after it starts. On Docker Desktop, naming the
* network at creation together with port bindings suppresses the published ports, so a
* container that publishes ports is created on the default bridge and connected afterwards.
* Any other daemon publishes them on the named network, so the container is created there and
* joins it alone. A daemon that cannot be asked is treated as Docker Desktop, and the answer is
* kept either way, so a container's create and its start always take the same path.
*/
private boolean connectsAfterStart(ContainerSpec spec) {
return spec.publishesPorts() && isDockerDesktop();
}
private boolean isDockerDesktop() {
Boolean known = dockerDesktop.get();
if (known != null) {
return known;
}
boolean desktop = DockerDaemon.operatingSystem(dockerClient).map(DockerDaemon::isDockerDesktop).orElse(true);
return dockerDesktop.compareAndSet(null, desktop) ? desktop : dockerDesktop.get();
}
private static boolean isContainerNetworkMode(String networkMode) {
return networkMode != null && networkMode.startsWith(CONTAINER_NETWORK_MODE_PREFIX);
}
@@ -0,0 +1,34 @@
package io.floci.aws.core.common.docker;
import com.github.dockerjava.api.DockerClient;
import org.jboss.logging.Logger;
import java.util.Locale;
import java.util.Optional;
/** What Floci reads about the Docker daemon it drives. */
public final class DockerDaemon {
private static final Logger LOG = Logger.getLogger(DockerDaemon.class);
private DockerDaemon() {
}
/**
* The daemon's {@code OperatingSystem} from {@code GET /info}, lower-cased, such as
* {@code docker desktop} or {@code ubuntu 24.04.1 lts}; empty when the daemon cannot be asked.
*/
public static Optional<String> operatingSystem(DockerClient dockerClient) {
try {
String os = dockerClient.infoCmd().exec().getOperatingSystem();
return Optional.ofNullable(os).map(value -> value.toLowerCase(Locale.ROOT));
} catch (Exception e) {
LOG.debugv("Could not read the Docker daemon's operating system: {0}", e.getMessage());
return Optional.empty();
}
}
public static boolean isDockerDesktop(String operatingSystem) {
return operatingSystem.contains("docker desktop");
}
}
@@ -3,6 +3,7 @@ package io.floci.aws.services.ec2;
import com.github.dockerjava.api.DockerClient;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.docker.ContainerDetector;
import io.floci.aws.core.common.docker.DockerDaemon;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -10,7 +11,6 @@ import org.jboss.logging.Logger;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Locale;
import java.util.Optional;
/**
@@ -107,7 +107,7 @@ public class ContainerNetworkReachability {
// Floci is containerised. The probe just proved container-to-container reachability,
// which is true even on Docker Desktop, where the host still cannot route there.
String backend = dockerBackend();
if (backend.contains("docker desktop")) {
if (DockerDaemon.isDockerDesktop(backend)) {
LOG.infov("Docker backend is {0}: container IPs are not routable from the host, so "
+ "EC2 public addresses stay on 127.0.0.1 with published ports. Set "
+ "FLOCI_SERVICES_EC2_CONTAINER_IPS_ROUTABLE=true to override.",
@@ -134,12 +134,6 @@ public class ContainerNetworkReachability {
}
private String dockerBackend() {
try {
String os = dockerClient.infoCmd().exec().getOperatingSystem();
return os == null ? "" : os.toLowerCase(Locale.ROOT);
} catch (Exception e) {
LOG.debugv("Could not read the Docker daemon's operating system: {0}", e.getMessage());
return "";
}
return DockerDaemon.operatingSystem(dockerClient).orElse("");
}
}
@@ -7,6 +7,7 @@ import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.command.CreateNetworkCmd;
import com.github.dockerjava.api.command.DisconnectFromNetworkCmd;
import com.github.dockerjava.api.command.InfoCmd;
import com.github.dockerjava.api.command.InspectContainerCmd;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.command.InspectNetworkCmd;
@@ -18,6 +19,7 @@ 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.Info;
import com.github.dockerjava.api.model.Network;
import com.github.dockerjava.api.model.NetworkSettings;
import com.github.dockerjava.api.model.Ports;
@@ -171,6 +173,62 @@ class ContainerLifecycleManagerNetworkTest {
verify(dockerClient, never()).removeContainerCmd(any(String.class));
}
@Test
void createAndStartPutsAPublishingContainerOnItsNetworkAloneOnDockerEngine() {
daemonRuns("Ubuntu 24.04.1 LTS");
when(dockerClient.startContainerCmd("container-id")).thenReturn(mock(StartContainerCmd.class));
when(inspectOf("container-id").getNetworkSettings()).thenReturn(mock(NetworkSettings.class));
manager().createAndStart(spec("floci-net", Map.of(8080, 18080), List.of()));
HostConfig hostConfig = createdHostConfig();
assertEquals("floci-net", hostConfig.getNetworkMode());
assertTrue(hostConfig.getPortBindings().getBindings().containsKey(ExposedPort.tcp(8080)));
verify(connectCmd, never()).exec();
}
@Test
void createAndStartConnectsAPublishingContainerAfterStartOnDockerDesktop() {
daemonRuns("Docker Desktop");
when(dockerClient.startContainerCmd("container-id")).thenReturn(mock(StartContainerCmd.class));
when(inspectOf("container-id").getNetworkSettings()).thenReturn(mock(NetworkSettings.class));
manager().createAndStart(spec("floci-net", Map.of(8080, 18080), List.of()));
assertNull(createdHostConfig().getNetworkMode());
verify(connectCmd).withNetworkId("floci-net");
verify(connectCmd).exec();
}
@Test
void createAndStartStillConnectsAPublishingContainerWhenTheDaemonAnswersOnlyAfterCreate() {
InfoCmd infoCmd = mock(InfoCmd.class);
Info info = mock(Info.class);
lenient().when(dockerClient.infoCmd()).thenReturn(infoCmd);
lenient().when(infoCmd.exec()).thenThrow(new RuntimeException("daemon busy")).thenReturn(info);
lenient().when(info.getOperatingSystem()).thenReturn("Ubuntu 24.04.1 LTS");
when(dockerClient.startContainerCmd("container-id")).thenReturn(mock(StartContainerCmd.class));
when(inspectOf("container-id").getNetworkSettings()).thenReturn(mock(NetworkSettings.class));
manager().createAndStart(spec("floci-net", Map.of(8080, 18080), List.of()));
assertNull(createdHostConfig().getNetworkMode());
verify(connectCmd).withNetworkId("floci-net");
verify(connectCmd).exec();
}
@Test
void createReconnectsAPublishingContainerWithItsLinkLocalEndpointOnDockerEngine() {
daemonRuns("Ubuntu 24.04.1 LTS");
manager().create(specWithLinkLocalIp(Map.of(8080, 18080)));
assertEquals("test-network", createdHostConfig().getNetworkMode());
InOrder order = inOrder(disconnectCmd, connectCmd);
order.verify(disconnectCmd).exec();
order.verify(connectCmd).exec();
}
@Test
void createLeavesNetworkAloneWithoutLinkLocalIps() {
manager().create(new ContainerSpec("busybox:stable"));
@@ -416,6 +474,14 @@ class ContainerLifecycleManagerNetworkTest {
return inspect;
}
private void daemonRuns(String operatingSystem) {
InfoCmd infoCmd = mock(InfoCmd.class);
Info info = mock(Info.class);
when(dockerClient.infoCmd()).thenReturn(infoCmd);
when(infoCmd.exec()).thenReturn(info);
when(info.getOperatingSystem()).thenReturn(operatingSystem);
}
private HostConfig createdHostConfig() {
ArgumentCaptor<HostConfig> hostConfig = ArgumentCaptor.forClass(HostConfig.class);
verify(createCmd).withHostConfig(hostConfig.capture());