Skip to content

[Bug]: getFirstMappedPort returns wrong port after adding secondary network #11779

@lmartelli

Description

@lmartelli

Module

Core

Testcontainers version

1.21.4

Using the latest Testcontainers version?

Yes

Host OS

Linux

Host Arch

x86

Docker version

Version:           29.4.3
 API version:       1.54
 Go version:        go1.26.2
 Git commit:        055a478
 Built:             Wed May  6 17:07:39 2026
 OS/Arch:           linux/amd64
 Context:           default

Server: Docker Engine - Community
 Engine:
  Version:          29.4.3
  API version:      1.54 (minimum version 1.41)
  Go version:       go1.26.2
  Git commit:       56be731
  Built:            Wed May  6 17:07:39 2026
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          v2.2.3
  GitCommit:        77c84241c7cbdd9b4eca2591793e3d4f4317c590
 runc:
  Version:          1.3.5
  GitCommit:        v1.3.5-0-g488fc13e
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0

What happened?

I configure a container like so :

Network defaultNetwork = new Network();
Network customNetwork = return new Network() {
				public String getId() { return cystomNetworkId; }
				public void close() {}
				public Statement apply(Statement base, Description description) { return null; }
			};

GenericContainer container = new GenericContainer<>(DockerImageName.parse("registry.ogosecurity.com/repository/ogo/traefik-ogo-proxy:latest"))
					.withNetwork(customNetwork)
					.withNetworkAliases("test-host")
					.withExposedPorts(7077);
container.start();
dockerClient.connectToNetworkCmd()
					.withContainerId(container.getContainerId())
					.withNetworkId(defaultNetwork.getId())
					.exec();

Then, when I ask the mapped port with container.getFirstMappedPort(), the returned port is not usable. docker ps shows a mapped port which is +1 compared to getFirstMappedPort().
It looks like adding a network remaps the exposed port, but testcontainer somewhat cached the first value.
Starting with defaultNetwork and then adding my customNetwork fixes the issue for me regarding the port (I can connect from the host using the given port), but then I can't use the network alias from another container the customNetwork.

Relevant log output

Additional Information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions