DEV Community

Cover image for Custom Subnet IP for docker0 Interface
Bruno do Nascimento Maciel
Bruno do Nascimento Maciel

Posted on • Edited on

Custom Subnet IP for docker0 Interface

Here is the problem, I want to deploy an API in my server but the server runs other services that conflict with the default IP that was given by default for docker0 interface. So I need to set up a custom subnet IP for that interface and put up some docker containers without creating new interfaces with the same subnet that is conflicting with the aforementioned services.

Docker Service Config

First, we need to set the custom subnet for the docker0 default interface. To do this we need to edit or create if it does not exist a configuration file for the docker service.
# vim /etc/docker/daemon.json
And put this as content:

{
    "bip": "10.10.0.1/24"
}
Enter fullscreen mode Exit fullscreen mode

After that we need to restart the docker service:
# service docker restart
After restart the docker service we can run ifconfig to see if the changes were applied:
Alt Text
As we can see in the image, the docker0 interface is set with the subnet that we have inserted in the daemon.json file.

Docker Compose

Now we have to set in our docker-compose.yml file, that we want to use the docker0 interface and not create some random new one. To do this you only need to add network_mode: bridge option to all your services inside docker-compose.yml file, like:

version: '3.3'

services:
    db:
        image: mysql:5.7
        restart: always
        environment:
            MYSQL_ROOT_PASSWORD: 'Lorem-Diem'
            MYSQL_USER: 'lorem'
            MYSQL_PASSWORD: 'Lorem-Ipsum'
        network_mode: bridge
        ports:
            - '3306:3306'
        volumes:
            - ./mysql_data:/var/lib/mysql

Enter fullscreen mode Exit fullscreen mode

And after that you can just build and put up your containers:

$ docker-compose up -d --build

Now, if you run ifconfig again you will see that none new interfaces were created.

If you want to see your container IP, get the container id using $ docker ps and run $ docker inspect <your container id> | grep -i ip.

Single Docker

If you want to start a single docker using the docker0 interface, you can add the --net bridge to your docker run command, like:

$ docker run -it -d --net bridge ubuntu:18.04 /bin/bash

The above command brings up a detached container running Ubuntu version 18.04 and calls the /bin/bash so that you can run ifconfig again in your host machine to see that the container is really using the default docker0 interface.

All the containers mentioned in this post will receive an IP address that fits the docker0 subnet.

Top comments (0)