'Why docker image is removed at the end of the tests when using testcontainers?

I'm using Testcontainers:

protected static JdbcDatabaseContainer<?> platformPostgresContainer = new PostgreSQLContainer<>("postgres:13")
//      .withReuse(true)
      .withInitScript("create-databases.sql");

Why without the .withReuse(true) the postgres:13 image sometimes disappears from Docker at the end of the tests?



Solution 1:[1]

This is by design, the lifecycle of containers managed by Testcontainers can be hooked into the test framework, but will ultimately not extend the life of the JVM process (unless the alpha feature resusable mode is used).

Solution 2:[2]

The image is deleted by Ryuk, if the environment variable TESTCONTAINERS_RYUK_DISABLED=true is not specified, then Testcontainers will start the Moby Ryuk container which in turn when will receive SIGTERM will remove all containers with label org.testcontainers=true, then will remove all images without containers (see the argument of cli.ImagesPrune from function prune in moby-ryuk/main.go). Thus, if the only postgres:13 containers where those created by Testcontainers, then after their remove, the postgres:13 image will have no associated containers and will be removed too by Ryuk.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kevin Wittek
Solution 2