Search code examples
dockernetwork-programmingdocker-composedocker-network

setting an ip rang/subnet for docker networking or not? which one is better?


I'm using docker compose for deploying applications (front/backend) on server and in compose file i defined two networks one for backend and one for frontend. here is my question which one is better :

One with specify network configuration:

...
networks:
 frontend:
  driver: bridge
  ipam:
   config:
   - subnet: 172.20.0.0/16
 backend:
  driver: bridge
  ipam:
   config:
   - subnet: 172.21.0.0/16
...

Or without specifying network configuration :

...
networks:
 frontend:
 backend:
...

I don't want a static ip for any one containers, i just use the name of containers/services to communicate between containers.

explanation about which one is better.


Solution

  • You should almost never specify the IP configuration you show. Docker can assign it automatically, and the IP addresses aren't accessible from outside of Docker; you have no reason to know them and you can't use them if you do explicitly set them.

    For almost all applications that run in Compose, you don't need to set networks: at all. Compose automatically creates a network named default for you, and if a container doesn't include a networks: block then it automatically gets assigned networks: [default]. That single shared network is just fine for anything where a Compose is the right management tool (where you probably have fewer than a dozen containers, all as part of a single combined application).

    The only exception is if your host network environment also uses the same reserved networks in 172.16.0.0/12 that Docker likes to use. If your host system is something like 172.18.12.34/16, and Docker wants to automatically create its own network on 172.18.0.0/16, then in that case only you might want to manually assign a non-conflicting CIDR block to the default network

    networks:
      default:
        ipam:
          config:
            - subnet: 172.19.0.0/16
    

    Networking in Compose in the Docker documentation has more information on what Compose knows how to set up on its own and on configuring the default network.