创建一个允许容器之间通信但不能访问Internet的网络

问题描述

如何使用testcontainers创建docker网络,

  • 允许网络中的所有容器相互通信
  • 允许容器将端口映射到主机
  • 但不允许容器访问互联网

我尝试使用internal网络进行此操作:

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();
}

但是,当我运行它时,我无法映射我的端口。引发异常:

Caused by: java.lang.IllegalArgumentException: Requested port (8024) is not mapped

如果我在没有withInternal(true)的情况下运行它,则可以正常工作,但是容器当然可以访问Internet。

解决方法

我认为您可以通过(a)创建常规网络,然后(b)在DROP防火墙链中添加DOCKER-USER规则来获得所需的东西:

iptables -I DOCKER-USER -j DROP

在我刚才的快速实验中,这使我能够映射容器的端口,但是阻止了容器访问Internet(因为此链是从FORWARD链中调用的,因为它阻止了容器通过托管到外部互联网。

,

花了几天时间尝试了不同的事情之后,我想到了一种可行的解决方案:

uniq_groups = unique(dat$group)

for (i in 1:length(uniq_groups)) {
p= ggplot(dat=dat[dat$group==uniq_groups[i],],aes(x= as.numeric(year))) +
  geom_line(aes(y= as.numeric(mean),color = "red")) + 
  geom_line(aes(y= as.numeric(sd),color = "blue")) + 
  ggtitle(uniq_groups[i])
ggsave(p,file=paste0("plot_",i,".png"),width = 14,height = 10,units = "cm")
} 

这会将容器的DNS设置为无效的IP,然后当您尝试在容器中发出HTTP请求时,它将抛出 /** * 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); }

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...