How can I create a docker network using testcontainers
which:
- allows for all containers in the network to communicate with each
- allows for containers to map ports to the host
- but does not allow containers to have access to the internet
I have tried to do this using an internal
network:
private Network generateInternalNetwork() {
// Consumer which operates on the final CreateNetworkCmd which will be run to
// make sure the 'internal' flag is set.
Consumer<CreateNetworkCmd> cmdModifier = (createNetworkCmd) -> {
createNetworkCmd.withInternal(true);
};
return Network.builder()
.createNetworkCmdModifier(cmdModifier)
.build();
}
However, when I run this I cannot have my port mapped. An exception is thrown:
Caused by: java.lang.IllegalArgumentException: Requested port (8024) is not mapped
If I run it without withInternal(true)
it works fine but of course the containers have internet access.
After spending a few days trying different things I have come up with a hack of a solution that kind-of works:
This sets the container's DNS to an invalid IP and then when you try to make a HTTP request in the container it will throw a
java.net.ConnectException
.