I am trying to simulate a network outage with testcontainers. I wanted to use a Socat container to expose the port, and then shot it down, and up again. I couldn't manage this as there are no halt.
How can I manage this?
That's easy!
You need 2 containers, SocatContainer (provided by Testcontainers) and your target container. Connect them (Socat & target) with a network, see examples here:
https://github.com/testcontainers/testcontainers-java/blob/bcecd5cd9f9325517fd45db585312df2624315bb/core/src/test/java/org/testcontainers/containers/NetworkTest.java
When you need to simulate an outage, simply disconnect your target from the network (by using the Docker client you get with DockerClientFactory.instance().client() and disconnectFromNetworkCmd).
After you verify that the outage is handled correctly, connect your target to the network with connectToNetworkCmd).
An alternative solution would be to use Toxiproxy from Shopify:
https://github.com/shopify/toxiproxy.
Start it in a container (with Testcontainers of course ;)) and use their Java client to apply the chaos operations.
The easiest way is via testcontainers support for toxiproxy (https://www.testcontainers.org/modules/toxiproxy/).
Copy-pasting from the above web page:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With