Search code examples
dockerdocker-composedocker-network

How to configure docker to avoid a specific address or subnet?


In our development environment, we manage 20+ containers with docker-compose files, but from time to time one of them acquires one IP from our network and we lost connectivity. When that happens, we manually shut down the container and the network.

Is there a way to configure docker to avoid that specific IP address or subnet when we add more containers?

Our docker version is:

Client: Docker Engine - Community
 Version:           19.03.12
 API version:       1.40
 Go version:        go1.13.10
 Git commit:        48a66213fe
 Built:             Mon Jun 22 15:45:36 2020
 OS/Arch:           linux/amd64
 Experimental:      false

Our docker-compose version is:

docker-compose version 1.25.4, build 8d51620a
docker-py version: 4.1.0
CPython version: 3.7.5
OpenSSL version: OpenSSL 1.1.0l  10 Sep 2019

The host OS is: Linux lin_env_int_2 4.15.0-112-generic #113-Ubuntu SMP Thu Jul 9 23:41:39 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux (Ubuntu 18.04.4 LTS)


Solution

  • If you have a larger infrastructure when this subnet collisions may occur then I would recommend creating your own docker network which would then host those containers.

    You can easily specify IP range for that docker network such that you can be sure that it doesn't overlap with any of your other networks.

    docker network create --subnet 10.10.0.0/16 mynet
    

    And run your containers with --network mynet

    docker container run -d -p 8080:80 --network mynet --name web nginx
    

    inspecting the container using docker container inspect

    "IPAddress": "10.10.0.2",
    

    In docker-compose, you can target the previously created network (mynet) like this

    version: "3.4"
    
    services:
      web:
        image: nginx
        ports:
          - "8888:80"
        networks:
          - mynet
    
    networks:
      mynet:
        external:
          name: mynet