Skip to main content

TestContainers固定容器端口

· 2 min read
orange
programmer on jvm platform

这篇文章的内容发生的背景和测试javaldapfailover有关.
测试failover需要启动两个ldap的容器并stop其中一个.
但是stop完之后遇到了一个问题当下次启动后分配的端口会变化(这是由于docker的内部机制导致的).
接下来将会介绍如何解决这个问题.

解决方案

启动容器时增加fixedExposedPort

val container = FixedHostPortGenericContainer<*>("<your-docker-image>")
container.withExposedPorts(389)
container.withFixedExposedPort(
TestSocketUtils.findAvailableTcpPort(),
389
) // we need to fix the port to make sure the port is the same when the container is restarted

注意事项

需要注意以下几点:

  • 创建FixedHostPortGenericContainer的实例来固定端口
    FixedHostPortGenericContainerTestContainers提供的一个GenericContainer的子类, 用来固定容器的端口
  • 使用TestSocketUtils.findAvailableTcpPort()获取一个可用的端口
    使用TestSocketUtils.findAvailableTcpPort()获取一个可用的端口确保host上的端口没有被占用

参考资料