使用 testcontainers 模拟数据库的网络中断

simulate network outage for database with testcontainers

我正在尝试使用测试容器模拟网络中断。 我想使用一个 Socat 容器来暴露端口,然后将其击落,然后再打开。我无法处理这个,因为没有停止。

我该如何管理?

这很简单!

你需要2个容器,SocatContainer(由Testcontainers提供)和你的目标容器。将它们(Socat 和 target)连接到网络,请参阅此处的示例:
https://github.com/testcontainers/testcontainers-java/blob/bcecd5cd9f9325517fd45db585312df2624315bb/core/src/test/java/org/testcontainers/containers/NetworkTest.java

当您需要模拟中断时,只需断开您的目标与网络的连接(通过使用 DockerClientFactory.instance().client()disconnectFromNetworkCmd 获得的 Docker 客户端)。

确认中断处理正确后,使用 connectToNetworkCmd 将目标连接到网络。

另一种解决方案是使用 Shopify 的 Toxiproxy:
https://github.com/shopify/toxiproxy。 在容器中启动它(当然是使用 Testcontainers ;))并使用他们的 Java 客户端来应用混沌操作。

最简单的方法是通过测试容器支持 toxiproxy (https://www.testcontainers.org/modules/toxiproxy/)。

从上面的网页复制粘贴:

E.g. // Create a common docker network so that containers can communicate
@Rule
public Network network = Network.newNetwork();

// the target container - this could be anything
@Rule
public GenericContainer redis = new GenericContainer("redis:5.0.4")
    .withExposedPorts(6379)
    .withNetwork(network);

// Toxiproxy container, which will be used as a TCP proxy
@Rule
public ToxiproxyContainer toxiproxy = new ToxiproxyContainer()
    .withNetwork(network);
// To simulate an outage you do:

final ToxiproxyContainer.ContainerProxy proxy = toxiproxy.getProxy(redis, 6379);
proxy.setConnectionCut(true);