Testcontainers restart of container without deleting it.

Tymur Kubai
2 min readJul 23, 2020

--

stop and start container

Testcontainers-java is great library.

But recently I was in need of testing behaviour when front-end lose conection with back-end server.

There was a discussion on github about it. Unfortunatelly discussion not lead anywhere, but I was able to find tips there. And due to issue was closed you just cant add your comment. So here we go.

Right now if you just stop() container, than it will be deleted imidiatelly afterward.

Which is OK if you don’t depend on previous state. Than you just can start() it again and keep going.

But if you depend on previous state(in memory DB) or as it was in my case, cointainer was included in custum docker-network. stop() and start() will leave you nowhere.

So in that case we just need to make one step back and use com.github.dockerjava than testcontainers use under the hood.

So the solution will be look like this https://gist.github.com/sirdir/8479cd0b8bc2fd89893d261a1be35d04

import com.github.dockerjava.api.DockerClient;
import org.junit.jupiter.api.Test;
import org.testcontainers.DockerClientFactory;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.Network;
import org.testcontainers.junit.jupiter.Testcontainers;
@Testcontainers
public class SomeClass {
@Test
void stopAndStartContainer() {
try (
Network network = Network.newNetwork();
GenericContainer<?> nginx = new GenericContainer("nginx:latest")
.withNetwork(network)
.withNetworkAliases("foo")
) {
nginx.start();
//starting UI
//.....
//doint some stuff with UI
DockerClient client = DockerClientFactory.lazyClient();
client.stopContainerCmd(nginx.getContainerId()).exec();
//asserting reconnection pooling behaviour on UI
client.startContainerCmd(nginx.getContainerId()).exec();
//asserting successful reconnection behaviour on UI
}
}
}

--

--