问题
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.
回答1:
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
来源:https://stackoverflow.com/questions/46548199/can-testcontainers-create-docker-network-for-me-if-it-does-not-exist