Search code examples
dockerdocker-compose

Provide static IP to docker containers via docker-compose


I'm trying to provide static IP address to containers. I understand that I have to create a custom network. I create it and the bridge interface is up on the host machine (Ubuntu 16.x). The containers get IP from this subnet but not the static I provided.

Here is my docker-compose.yml:

version: '2'

services:
  mysql:
    container_name: mysql
    image: mysql:latest
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=root
    ports:
     - "3306:3306"
    networks:
     - vpcbr

  apigw-tomcat:
    container_name: apigw-tomcat
    build: tomcat/.
    ports:
     - "8080:8080"
     - "8009:8009"
    networks:
     - vpcbr
    depends_on:
     - mysql

networks:
  vpcbr:
    driver: bridge
    ipam:
     config:
       - subnet: 10.5.0.0/16
         gateway: 10.5.0.1
         aux_addresses:
          mysql: 10.5.0.5
          apigw-tomcat: 10.5.0.6

The containers get 10.5.0.2 and 10.5.0.3, instead of 5 and 6.


Solution

  • Note that I don't recommend a fixed IP for containers in Docker unless you're doing something that allows routing from outside to the inside of your container network (e.g. macvlan). DNS is already there for service discovery inside of the container network and supports container scaling. And outside the container network, you should use exposed ports on the host. With that disclaimer, here's the compose file you want:

    version: '2'
    
    services:
      mysql:
        container_name: mysql
        image: mysql:latest
        restart: always
        environment:
          - MYSQL_ROOT_PASSWORD=root
        ports:
         - "3306:3306"
        networks:
          vpcbr:
            ipv4_address: 10.5.0.5
    
      apigw-tomcat:
        container_name: apigw-tomcat
        build: tomcat/.
        ports:
         - "8080:8080"
         - "8009:8009"
        networks:
          vpcbr:
            ipv4_address: 10.5.0.6
        depends_on:
         - mysql
    
    networks:
      vpcbr:
        driver: bridge
        ipam:
         config:
           - subnet: 10.5.0.0/16
             gateway: 10.5.0.1