Looks like I need a network because I would like to reference one container by hostname from another.
I could also use the --link
but it is deprecated and can disappear soon. That's why I wonder if Testcontainers can create a docker network for me.
With command line I would just execute docker network create bridge2
and then I can start containers like this:
docker run -it --rm --net=bridge2 --name alpine1 alpine
docker run -it --rm --net=bridge2 --name alpine2 alpine
and resolve nslookup alpine2
from alpine1
container.
If I try to use default --net=bridge
network or skip --net
option (which is actually the same) referencing by name will not work.
By default Compose sets up a single network for your app. Each container for a service joins the default network and is both reachable by other containers on that network, and discoverable by them at a hostname identical to the container name.
Out of the box, Docker creates three networks: bridge – An automatically generated network with a subnet and a gateway. host – Allows a container to attach to the host's network. none – A container-specific network stack that lacks a network interface.
When you start Docker, a default bridge network (also called bridge ) is created automatically, and newly-started containers connect to it unless otherwise specified. You can also create user-defined custom bridge networks. User-defined bridge networks are superior to the default bridge network.
Docker includes support for networking containers through the use of network drivers. By default, Docker provides two network drivers for you, the bridge and the overlay drivers. You can also write a network driver plugin so that you can create your own drivers but that is an advanced task.
Yes, you can create networks with TestContainers. We're going to document it soon, but it's as simple as:
First, create a network:
@Rule
public Network network = Network.newNetwork();
Then, configure your containers to join it:
@Rule
public NginxContainer nginx = new NginxContainer<>()
.withNetwork(network) // <--- Here
.withNetworkAliases("nginx") // <--- "hostname" of this container
.withCustomContent(contentFolder.toString());
@Rule
public BrowserWebDriverContainer chrome = new BrowserWebDriverContainer<>()
.withNetwork(network) // <--- And here
.withDesiredCapabilities(DesiredCapabilities.chrome());
Now Nginx container will be visible to Chrome as "http://nginx/".
The same example in our tests:
https://github.com/testcontainers/testcontainers-java/blob/540f5672df90aa5233dde1dde7e8a9bc021c6e88/modules/selenium/src/test/java/org/testcontainers/junit/LinkedContainerTest.java#L27
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With