如果不存在,Testcontainers可以为我创建docker网络吗? [英] Can Testcontainers create docker network for me if it does not exist?
问题描述
好像我需要一个网络,因为我想通过主机名引用另一个容器中的一个容器.
Looks like I need a network because I would like to reference one container by hostname from another.
我也可以使用--link
,但是它已被弃用,并且很快就会消失.这就是为什么我想知道Testcontainers是否可以为我创建一个docker网络.
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.
通过命令行,我只需执行docker network create bridge2
,然后就可以启动这样的容器了:
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
并从alpine1
容器解析nslookup alpine2
.
如果我尝试使用默认的--net=bridge
网络或跳过--net
选项(实际上是相同的),则按名称引用将不起作用.
If I try to use default --net=bridge
network or skip --net
option (which is actually the same) referencing by name will not work.
推荐答案
是的,您可以使用TestContainers创建网络.我们将尽快对其进行记录,但是它很简单:
Yes, you can create networks with TestContainers. We're going to document it soon, but it's as simple as:
首先,创建一个网络:
@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());
现在Nginx容器将在Chrome中显示为" http://nginx/".
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
这篇关于如果不存在,Testcontainers可以为我创建docker网络吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!