Skip to content

fix: keep getMappedPort correct after network attach/detach - #11959

Open
arimu1 wants to merge 1 commit into
testcontainers:mainfrom
arimu1:fix/11779-mapped-port-after-network
Open

fix: keep getMappedPort correct after network attach/detach#11959
arimu1 wants to merge 1 commit into
testcontainers:mainfrom
arimu1:fix/11779-mapped-port-after-network

Conversation

@arimu1

@arimu1 arimu1 commented Aug 5, 2026

Copy link
Copy Markdown

What does this PR do?

Fixes getMappedPort / getFirstMappedPort returning a stale host port after Docker reassigns published ports when networks change.

Root cause: ContainerState.getMappedPort read bindings from the start-time cached getContainerInfo(). After attaching another network (or disconnect/reconnect), Docker may publish a different host port while the cache still holds the original value — matching issue #11779.

Fix: Resolve port bindings from a live inspect via getCurrentContainerInfo() so reported host ports always match Docker's current state.

Why not only document / refresh manually?

Issue #11779 is a functional correctness bug for a common post-start network workflow. Callers of getFirstMappedPort() reasonably expect Docker's current published port. Wait strategies resolve mapped ports once before polling (not per-poll), so the extra inspect cost is bounded for typical usage.

Related change history

This PR re-applies the live-inspect approach with focused regression coverage for the #11779 scenario.

How was it tested?

  • Unit (no Docker): ContainerStateTest
    • getMappedPortUsesCurrentContainerInfo
    • getFirstMappedPortUsesCurrentContainerInfo
  • Integration (Docker): NetworkTest.WithoutRules
    • getFirstMappedPortRemainsCorrectAfterSecondaryNetworkAttach (issue repro)
    • getMappedPortReflectsDockerRemapAfterNetworkDisconnectReconnect (forces host-port remap)
  • ./gradlew :testcontainers:test --tests org.testcontainers.containers.ContainerStateTest --tests org.testcontainers.containers.NetworkTest
  • Temurin 21, Colima/Docker 29.x on macOS aarch64

Fixes #11779

getMappedPort/getFirstMappedPort used the start-time cached
container inspect, so host ports became stale after Docker reassigned
them (network disconnect/reconnect, and some secondary network
attach scenarios). Resolve bindings from getCurrentContainerInfo()
instead.

Fixes testcontainers#11779
@arimu1
arimu1 requested a review from a team as a code owner August 5, 2026 15:12
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.

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

1 participant