创建一个允许容器之间通信但不能访问Internet的网络 [英] Creating a network which allows communication between containers but no internet access
问题描述
如何使用 testcontainers
创建一个docker网络,
- 允许在其中使用所有容器网络与每个容器进行通信
- 允许容器将端口映射到主机
- ,但不允许容器访问互联网
我尝试使用内部
网络执行此操作:
< pre $ = lang-java prettyprint-override>
私有网络generateInternalNetwork(){
//在最终CreateNetworkCmd上运行的使用者,将运行到
//确保设置了内部标志。
Consumer< CreateNetworkCmd> cmdModifier =(createNetworkCmd)-> {
createNetworkCmd.withInternal(true);
};
返回Network.builder()
.createNetworkCmdModifier(cmdModifier)
.build();
}
但是,当我运行此命令时,无法映射我的端口。引发异常:
原因:java.lang.IllegalArgumentException:未映射请求的端口(8024)
如果我在没有 withInternal(true)
的情况下运行它,则可以正常工作,但是容器当然可以访问Internet。
花了几天时间尝试了不同的事情后,我想到了一种可行的解决方案:
/ **
*为给定容器设置无效的DNS。
*这是一种解决方法,因此容器无法访问
*互联网。
* /
void setInvalidDns(){
GenericContainer<?>容器= getContainer();
Consumer< CreateContainerCmd>修饰符=(cmd)-> {
//使用垃圾DNS修改配置。
字符串invalidDns = 255.255.255.255;
HostConfig hostConfig = cmd.getHostConfig();
hostConfig.withDns(invalidDns);
cmd.withHostConfig(hostConfig);
};
container.withCreateContainerCmdModifier(modifier);
}
这会将容器的DNS设置为无效IP,然后尝试在其中发出HTTP请求容器将抛出 java.net.ConnectException
。
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:
/**
* Set an invalid DNS for the given container.
* This is done as a workaround so that the container cannot access
* the internet.
*/
void setInvalidDns() {
GenericContainer<?> container = getContainer();
Consumer<CreateContainerCmd> modifier = (cmd) -> {
// Amend the config with the garbage DNS.
String invalidDns = "255.255.255.255";
HostConfig hostConfig = cmd.getHostConfig();
hostConfig.withDns(invalidDns);
cmd.withHostConfig(hostConfig);
};
container.withCreateContainerCmdModifier(modifier);
}
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
.
这篇关于创建一个允许容器之间通信但不能访问Internet的网络的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!