Untitled
unknown
plain_text
9 months ago
1.5 kB
18
Indexable
import org.testcontainers.containers.PostgreSQLContainer
import org.testcontainers.utility.DockerImageName
import com.github.dockerjava.api.model.*
import org.testcontainers.DockerClientFactory
fun createOrReusePostgres(): PostgreSQLContainer<Nothing> {
val dockerClient = DockerClientFactory.lazyClient()
val containers = dockerClient.listContainersCmd()
.withShowAll(true)
.exec()
.filter { it.labels?.get("tc.reuse.name") == "shared-postgres" }
return if (containers.isNotEmpty()) {
println("🔁 Reusing existing PostgreSQL container")
// Możemy połączyć się po hostzie + porcie
val mappedPort = containers.first().ports.firstOrNull { it.privatePort == 5432 }?.publicPort
?: error("No mapped port found")
object : PostgreSQLContainer<Nothing>(DockerImageName.parse("postgres:15")) {}.apply {
withReuse(true)
withDatabaseName("test")
withUsername("user")
withPassword("pass")
setPortBindings(listOf("$mappedPort:5432")) // <-- łączymy się z istniejącym
// UWAGA: tu nie robimy .start() bo kontener już działa!
}
} else {
println("🚀 Starting new PostgreSQL container")
PostgreSQLContainer<Nothing>("postgres:15").apply {
withDatabaseName("test")
withUsername("user")
withPassword("pass")
withReuse(true)
withLabel("tc.reuse.name", "shared-postgres")
start()
}
}
}
Editor is loading...
Leave a Comment