简体   繁体   中英

WebDriver container cannot access DockerComposeContainer services

I am trying to use the testcontainers java library to test a web app defined with docker-compose.

I can successfully expose services from the DockerComposeContainer and query them with 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.

How do I make webdriver access the host network to access the exposed services?

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). In case of the BrowserWebDriverContainer , this means localhost won't work. 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)
  2. You can use Docker networks to connect the containers to each other.

Testcontainers recently introduced Docker Network support, but Docker-Compose container is still lacking this feature ATM.

You can however manually connect them like this (sorry for Groovy code example, but I think the approach is clear):

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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