Skip to content

[Enhancement]: Allow custom host aliases in addition to "host.testcontainers.internal" #9922

Open
@ccobham

Description

@ccobham

Module

Core

Proposal

Summary

Testcontainers currently supports network access to the underlying host by forwarding to ports specified by Testcontainers.exposeHostPorts. If the container is configured with host access (withHostAccess(true)), then an additional host entry is added with a hostname host.testcontainers.internal and IP address corresponding to the port forwarding container at startup.

We would like the ability to define custom host aliases in addition to the default host.testcontainers.internal option.

Use Case

We are using Testcontainers for integration testing single sign-on login flows in which Selenium browser WebDriver containers interact with the application under test (AUT). In this scenario, the user is redirected to different identity providers based upon the request hostname. Backchannel requests from the AUT to the identity providers are running outside of the Docker network while front channel requests in Selenium run inside the Docker network. This requires a lot of brittle/nasty reverse proxy / DNS server configuration we'd like to avoid. We would prefer not to run the AUT in Docker.

Implementation

PortForwardingContainer.java

public enum PortForwardingContainer {
   
  INSTANCE;

  private final Set<String> hostAliases = ConcurrentHashMap.newKeySet();

  PortForwardingContainer() {
    addHostAlias(GenericContainer.INTERNAL_HOST_HOSTNAME);
  }

  void addHostAlias(String hostAlias) {
    this.hostAliases.add(hostAlias);
  }

  Set<String> getHostAliases() {
    return hostAliases;
  }

  ...

}

Testcontainers.java

@UtilityClass
public class Testcontainers {

   public void addHostAliases(String... hostAliases) {
    for (String hostAlias : hostAliases) {
      PortForwardingContainer.INSTANCE.addHostAlias(hostAlias);
    }
  }

  ...

}

GenericContainer.java

@Data
public class GenericContainer<SELF extends GenericContainer<SELF>> ... {

  ...

  if (hostAccessible) {
    PortForwardingContainer.INSTANCE.start();
  }
  PortForwardingContainer.INSTANCE
    .getNetwork()
    .ifPresent(network -> PortForwardingContainer.INSTANCE.getHostAliases()
      .forEach(hostAlias -> withExtraHost(hostAlias, network.getIpAddress()))
    );

  ...
}

Usage

  Testcontainers.exposeHostPorts(localServerPort);
  Testcontainers.addHostAliases("example1.test", "example2.test");

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions