testcontainers-node: Port mapping for ipv4 & ipv6 can cause different ports to be mapped and getMappedPort function will return wrong port

Expected Behaviour

I want to get a predictable port number and host,

the problem seems to be in this file - https://github.com/testcontainers/testcontainers-node/blob/main/packages/testcontainers/src/utils/bound-ports.ts

method - resolveHostPortBinding line - return hostPortBindings[0].hostPort;

Actual Behaviour

We have tests that are running in parallel and it was quite hard to identify that issue, because locally on mac os everything is fine, but on latest ubuntu the problem auto assigning port appear

https://github.com/testcontainers/testcontainers-dotnet/issues/825 - same issue for .net

So what happening:

  1. Starting a redis container (doesn’t matter which one, it just an example)
  2. withExposedPorts(6389) - let docker to auto assign host port
  3. calling getMappedPort function -> may return ipv4 or ipv6 port, depends on your luck

Testcontainer Logs …

Steps to Reproduce

  1. In this environment ubuntu 22
  2. With this config.
  3. Run ‘…’
  const container = await new GenericContainer(
    `${options.imageName}:${options.imageTag}`,
  )
    .withExposedPorts(6379)
    .start();

  // eslint-disable-next-line no-console
  console.timeEnd(`start redis`);

  const redisConfig = {
    port: container.getMappedPort(6379),
    host: 'localhost',
  } satisfies RedisStartedConfig;

  1. Run docker ps, and see that there are 2 ports actually

Environment Information

  • Operating System: ubuntu
  • Docker Version: 24+
  • Node version: 20+
  • Testcontainers version: 10.8.1

we temporary fixed it by retrieving ipv4 port from the docker inspect info:

import { StartedTestContainer } from 'testcontainers/build/test-container';

export function retrievePortFromBinding(
  container: StartedTestContainer,
  sourcePort: number,
): number {
  return Number.parseInt(
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    (container as never as any).inspectResult.NetworkSettings.Ports[
      `${sourcePort}/tcp`
    ].find((p: { HostIp: string; HostPort: string }) => p.HostIp === '0.0.0.0')
      .HostPort,
  );
}

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 2
  • Comments: 15

Most upvoted comments

Thanks for raising, I’ll need to look into it. Testcontainers resolves a list of host IPs, the order of which is determined by several factors like node version and OS. When we get the mapped port we probably need to find the port where the host matches the order, similar as you’ve done

@cristianrgreco Yeah it’s Ubuntu 24.04 runners on Github Actions. Image

We have a few different instances where we would call up testcontainers and it’s always in the same order:

await new PostgreSqlContainer('postgres:16').start()
await new RedisContainer('redis:7.0').start();

I tried switching the order and it still always binds redis with a different port on ipv6.

We ended it catching it because localhost resolves to both the ipv4 and ipv6 loopback ip on ubuntu and sometimes our tests would try to connect to the ipv6 address, but getConnectionUrl always returns redis://localhost:${ipv4-Port} and so our tests would say that it couldn’t connect to that port (since it’s going over ipv6 which was listening on a different port).

root@86594b02c8ea:/# host localhost
localhost has address 127.0.0.1
localhost has IPv6 address ::1

I’ll see if I can get some time this week to try directly on an Ubuntu VM directly with Docker to reproduce this.

I’m seeing this issue cause intermittent test failures in GitHub actions

These are the running containers when the test fails

  81aab0f5e111   postgres                    "docker-entrypoint.s…"   Less than a second ago   Up Less than a second   0.0.0.0:32788->5432/tcp, :::32787->5432/tcp   cranky_mayer
  81c23a01b865   postgres                    "docker-entrypoint.s…"   5 seconds ago            Up 4 seconds            0.0.0.0:32787->5432/tcp, :::32786->5432/tcp   nostalgic_williams
  23bcd23c1dbe   redis                       "docker-entrypoint.s…"   9 seconds ago            Up 8 seconds            0.0.0.0:32786->6379/tcp, :::32785->6379/tcp   strange_bartik
  b6d58a85bed1   postgres                    "docker-entrypoint.s…"   10 seconds ago           Up 9 seconds            0.0.0.0:32785->5432/tcp, :::32784->5432/tcp   nostalgic_zhukovsky
  b872239ad8e8   testcontainers/ryuk:0.5.1   "/bin/ryuk"              About a minute ago       Up About a minute       0.0.0.0:32773->8080/tcp, :::32773->8080/tcp   testcontainers-ryuk-18a2a870b94d

And then my test is trying to connect to 32785

  @@ Checking TCP connection to Redis... localhost 32785

which turns out to be postgres instead of redis on ipv4, I assume thats a chance thing

Yep I think docker returns the ports in random order, but we should be able to find the one we want by host