TestContainers固定容器端口
· 2 min read
这篇文章的内容发生的背景和测试java
的ldap
的failover
有关.
测试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的实例来固定端口
FixedHostPortGenericContainer
是TestContainers
提供的一个GenericContainer
的子类, 用来固定容器的端口 - 使用
TestSocketUtils.findAvailableTcpPort()
获取一个可用的端口
使用TestSocketUtils.findAvailableTcpPort()
获取一个可用的端口确保host
上的端口没有被占用