Saturday 26 June 2021

Defining Custom IP range for Docker Containers

 I feel or I would recommend, it is always good to go with custom subnet IP range for your docker containers and you would need it for many reasons:

  1. What id default IP ranges are not available
  2. You need to add the range/IP to your firewall but don’t know because of it’s dynamic nature. etc.

There are two ways you can do it and I’m saying it two ways because you would need it if you are dealing with docker containers in windows OS.

  1. Define it with Docker-Compose.yaml file.
For Linux:networks:
mycustomnet:
driver: bridge
ipam:
config:
- subnet: 20.5.0.0/24
For Windows:networks:
mycustomnet:
driver: nat
ipam:
config:
- subnet: 20.5.0.0/24

So above definition will create a name subnet under bridge/nat driver and you can use this defined subnet for your containers and your containers will always use IP from the above mentioned range only.

But this is a problem with Windows OS. In windows OS this defined network (in this case mycustomnet) will get disappear with restarting of windows OS. Aah it makes me frustrated when I faced this and unfortunately there is no solution available neither from Docker or Windows (at lease I didn’t find it as of now) and this is where I was forced to choose second approach which preferably I won’t recommend.

2. Define it via Docker Daemon.json

For windows:{"fixed-cidr": "20.5.0.0/16"}For Linux:{"default-address-pools":[
{"base":"20.5.0.0/16","size":24}
]
}

Above settings will change the default network IP range to 20.5.0.0/16 in windows as well as in Linux but in Linux I get extra advantage to mention the /24 range to be used out of /16 by creating a new named subnet. So in linux if you do >>docker network ls then you will see the defined name network as dockerartifacts_service or similar.

Since there is no problem with Linux so I would always recommend the first approach for Linux machine.

Important Note:
If you are doing the second approach for any reason, then don’t forget to delete the existing net and restart the docker engine and to do this you can use powershell command for windows as:

Get-HNSNetwork | Remove-HNSNetwork -Verbose
Restart-Service Docker -Verbose
Verbose will display the result and it is optional in command

No comments:

Post a Comment