Search code examples
dockerdocker-composedocker-network

How do I define and assign Subnet and IP addresses to Containers using Docker compose


I think what I am trying to do is straight forward, but reading through the docker compose documentation section on Networking https://docs.docker.com/compose/networking/ I find no useful information :(

I want to create 2 subnets (this could be more in the future - but for now, let's have it at two) and be able to manually assign IP addresses from each subnet to the container I specify in docker-compose.

How can this be done?


Solution

  • Use this compose file, you can add as many n/w's you want:-

    version: '2'
    services:
      mysql:
        container_name: mysql
        image: mysql:latest
        ports:
         - "3306:3306"
        networks:
          mgmnt:
            ipv4_address: "192.168.80.5"
      tomcat:
        container_name: tomcat
        image: tomcat:latest
        ports:
         - "8080:8080"
         - "8009:8009"
        networks:
          mgmnt:
            ipv4_address: "192.168.80.6"
          local:
            ipv4_address: "10.10.0.10"  
        depends_on:
         - mysql
    
    networks:
      mgmnt:
        driver: bridge
        ipam:
         config:
           - subnet: 192.168.0.0/16
             gateway: 192.168.0.1
      local:
        driver: bridge
        ipam:
         config:
           - subnet: 10.10.0.0/16
             gateway: 10.10.0.1