【发布时间】:2021-09-07 14:45:59
【问题描述】:
我正在尝试使用 GenericContainer 启动自定义 docker 容器。 启动容器后,我想执行来自测试类的 http 请求。 我看到了这个错误:
INFO: Exposed ports: 9000
java.net.ConnectException: Failed to connect to localhost/0:0:0:0:0:0:0:1:9000
at org.testcontainers.shaded.okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.java:265)
Caused by: java.net.ConnectException: Connection refused (Connection refused)
at java.base/java.net.PlainSocketImpl.socketConnect(Native Method)
端口似乎已绑定:
docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
f311467dbd25 foo.bar.com/abc-def/testcontainer:4.30.65 "/bin/sh -c 'exec /o…" About a minute ago Up About a minute 0.0.0.0:55164->9000/tcp, :::55164->9000/tcp, 0.0.0.0:55163->9001/tcp, :::55163->9001/tcp happy_jepsen
我正在使用以下代码创建容器:
myContainerInstance = new GenericContainer<>(MY_CONTAINER_IMAGE)
.withNetworkAliases("foo")
.withCreateContainerCmdModifier(createContainerCmd -> createContainerCmd.withHostName("foo"))
.waitingFor(new WaitAllStrategy().withStrategy(new LogMessageWaitStrategy().withRegEx(".*Listening for HTTP on.*"))
.withStartupTimeout(Duration.ofMinutes(4)))
.withExposedPorts(9000)
客户端代码:
OkHttpClient client = new OkHttpClient();
String url = "http://localhost:9000/testget";
String output = run(url);
logger.info("Response is: " + output);
}
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.addHeader("Content-type", "application/json")
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
其他细节:
- lsof -i :9000 在我的本地机器上没有显示任何绑定端口
- waitForHttpPort 的等待策略不起作用(容器启动超时)
如果能帮助我找出原因,我将不胜感激。
【问题讨论】:
标签: java docker junit dockerfile testcontainers