简体   繁体   English

WebDriver容器无法访问DockerComposeContainer服务

[英]WebDriver container cannot access DockerComposeContainer services

I am trying to use the testcontainers java library to test a web app defined with docker-compose. 我正在尝试使用testcontainers Java库来测试使用docker -compose定义的Web应用程序。

I can successfully expose services from the DockerComposeContainer and query them with RestTemplate. 我可以成功地从DockerComposeContainer公开服务,并使用RestTemplate查询它们。

    String url = format(
        "http://%s:%s",
        environment.getServiceHost("web_1", 8080),
        environment.getServicePort("web_1", 8080)
    );

    ResponseEntity<String> response = template.getForEntity(url, String.class);

However, when I try to access the service through the webdriver I get a Connection Refused error - "localhost refused to connect". 但是,当我尝试通过网络驱动程序访问服务时,出现“拒绝连接”错误-“本地主机拒绝连接”。

@Rule
public BrowserWebDriverContainer chrome = new BrowserWebDriverContainer()
    .withDesiredCapabilities(DesiredCapabilities.chrome());



    RemoteWebDriver driver = chrome.getWebDriver();
    driver.get(url);

I think the webdriver 'localhost' is still localhost inside its container, not the host where the services are exposed. 我认为webdriver'localhost'仍是其容器内的localhost,而不是公开服务的主机。

How do I make webdriver access the host network to access the exposed services? 如何使webdriver访问主机网络以访问公开的服务?

The URL you are building up is used to access the container from your host system (and so it will use localhost and mapped ports). 所建立的URL用于从主机系统访问容器(因此它将使用localhost和映射的端口)。 In case of the BrowserWebDriverContainer , this means localhost won't work. 如果使用BrowserWebDriverContainer ,则意味着localhost将无法工作。 There are two options: 有两种选择:

  1. You can use the mapped ports and access the host from the BrowserWebDriverContainer via the Docker host network (which might have an ip like 172.0.0.1) 您可以使用映射的端口,并通过Docker主机网络(可能具有一个IP,例如172.0.0.1)从BrowserWebDriverContainer访问主机。
  2. You can use Docker networks to connect the containers to each other. 您可以使用Docker网络将容器彼此连接。

Testcontainers recently introduced Docker Network support, but Docker-Compose container is still lacking this feature ATM. Testcontainers最近引入了对Docker Network的支持,但是Docker-Compose容器仍然缺少此功能的ATM。

You can however manually connect them like this (sorry for Groovy code example, but I think the approach is clear): 但是,您可以像这样手动连接它们(对不起,Groovy代码示例,但我认为方法很明确):

String network = findNetworkIdOfService("vote")
chrome.withNetworkMode(network)

private String findNetworkIdOfService(String service) {
        environment.ambassadorContainers.find {
            it.key.contains(service)
        }.value.containerInfo.networkSettings.networks.values().first().networkID
}

You also need to omit the @Rule annotation and start the container manually. 您还需要省略@Rule批注并手动启动容器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM