8

Looks like I need a network because I would like to reference one container by hostname from another.

I could also use the --link but it is deprecated and can disappear soon. That's why I wonder if Testcontainers can create a docker network for me.

With command line I would just execute docker network create bridge2 and then I can start containers like this:

docker run -it --rm --net=bridge2 --name alpine1 alpine
docker run -it --rm --net=bridge2 --name alpine2 alpine

and resolve nslookup alpine2 from alpine1 container.

If I try to use default --net=bridge network or skip --net option (which is actually the same) referencing by name will not work.

Kirill
  • 6,762
  • 4
  • 51
  • 81
  • Is docker-compose an option for you? – Yannic Hamann Oct 03 '17 at 15:32
  • @YannicHamann no, because looks like with Testcontaiers compose I can only work with exposed port and won't be able to execute arbitrarily commands for example. There are many limitations with compose. – Kirill Oct 03 '17 at 15:34

1 Answers1

12

Yes, you can create networks with TestContainers. We're going to document it soon, but it's as simple as:

First, create a network:

@Rule
public Network network = Network.newNetwork();

Then, configure your containers to join it:

@Rule
public NginxContainer nginx = new NginxContainer<>()
        .withNetwork(network) // <--- Here
        .withNetworkAliases("nginx") // <--- "hostname" of this container
        .withCustomContent(contentFolder.toString());

@Rule
public BrowserWebDriverContainer chrome = new BrowserWebDriverContainer<>()
        .withNetwork(network) // <--- And here
        .withDesiredCapabilities(DesiredCapabilities.chrome());

Now Nginx container will be visible to Chrome as "http://nginx/".

The same example in our tests:
https://github.com/testcontainers/testcontainers-java/blob/540f5672df90aa5233dde1dde7e8a9bc021c6e88/modules/selenium/src/test/java/org/testcontainers/junit/LinkedContainerTest.java#L27

bsideup
  • 2,845
  • 17
  • 21