gpt4 book ai didi

Java Testcontainers - 无法连接到暴露的端口

转载 作者:行者123 更新时间:2023-12-02 18:27:31 38 4
gpt4 key购买 nike

我使用 javax.mail 实现了一个 POP3 服务器和客户端,只是为了尝试与 Docker 进行集成测试。所以我基于 openjdk:8-jre 镜像创建了两个 Docker 镜像,并将我的 jars 复制到它们并启动它。根据我的配置(见下文),它正在工作。他们正在互相交谈。

但是由于想要进行多个集成测试,为每个测试构建一个镜像并启动它们将是乏味的。我也不知道如何自动化结果。
但后来我偶然发现了 TestContainers,这似乎在实现这些测试时会有很大帮助。

所以我开始将这些测试移植到 TestContainers,使用我的 POP3 服务器镜像作为 GenericContainer 并在 JUnit 测试方法中启动我的 POP3 客户端类。我公开了 POP3 服务器正在监听的端口 24999。但是当我尝试连接到服务器时,出现以下错误:

com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 32782; timeout -1;
nested exception is:
java.net.ConnectException: Connection refused
...

我在 TestContainers 中可能缺少一些设置。请你帮助我好吗。

这是我正在使用的代码:
public class DockerPop3AutocryptKeyProvidingAndReceivingTest {
@Test
public void test() throws InterruptedException {
GenericContainer container = new GenericContainer<>("immerfroehlich/emailfilter:latest")
.withExposedPorts(24999);

container.start();

String host = container.getContainerIpAddress();
String port = container.getFirstMappedPort().toString();

//The following is simplified, but copied from the working jar used in the Docker Client image/container
MyPOP3Client client = new MyPOP3Client(host, port);
client.connect();

container.stop();
}
}

这就是我创建 Docker 镜像的方式:
FROM openjdk:8-jre

ADD build/distributions/MyPOP3Server.tar . #This is where I have packeded all the needed files to. It gets unpackeded by Docker.
#EXPOSE 24999 #I tried both with and without this expose
WORKDIR /MyPOP3Server/bin
ENTRYPOINT ["sh","MyPOP3Server"] #Executes the shell script wich runs java with my jar

这是在 Server Jar 中运行的代码的简化版本:
MyPOP3Server server = new MyPOP3Server();
server.listenToPort(24999);

请告诉我我错过了什么。这里有什么问题?

谢谢和亲切的问候。

最佳答案

尝试添加 http 检查。

 new GenericContainer<>("immerfroehlich/emailfilter:latest")
.withExposedPorts(24999)
.waitingFor(new HttpWaitStrategy().forPort(24999)
.withStartupTimeout(Duration.ofMinutes(5)));

您的容器可能已启动,但您正在尝试在服务器初始化之前进行连接。

此外,注册一个日志附加程序以查看容器内服务器的情况。
 .withLogConsumer(new Slf4jLogConsumer(LoggerFactory.getLogger(
DockerPop3AutocryptKeyProvidingAndReceivingTest.class)))

关于Java Testcontainers - 无法连接到暴露的端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58202705/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com