how to properly specify an IP for a docker contain

2019-02-28 20:32发布

问题:

I'm trying to explicitly specify an IP address for my docker container in the following way:

sudo docker run -it -p 172.17.0.2:10000:10000 -p 9000:9000 -p 9090:9090 -v /home/eugene/dev/shared:/opt/shared -d eugene/dev_img_1.3

I'm getting the following error:

Error response from daemon: Cannot start container b2242e5da6e1b701ba4880f25fa8d465d5f008787b49898ad9e46eb26e417e48: port has already been allocated

I really do not care about port 10000. My goal is to have a specific container IP of my choosing, as well as to have ports 9000 and 9090 exposed to the host.

I have looked at some other questions, but did not see a clear syntax to do this

回答1:

The -p argument is used to forward ports from the container to the host, not for assigning IPs.

There is no easy way to assign a fixed IP to a Docker container and I would strongly advise you not to try. Instead re-architect your system so that it isn't dependent on a fixed IP. If this really isn't possible, I think you can choose an IP by using the LXC execution driver and various flags, but I would strongly recommend against this.



回答2:

You can assign a fixed ip using pipework, but it's not "the docker way". I would agree with Adrian. Re-design away from fixed IP's.



回答3:

This can be done in different ways.

You can edit your system-wide Docker server settings (by editing DOCKER_OPTS in /etc/default/docker) and add the option --ip=IP_ADDRESS in Ubuntu and then restart your server. If you are using only 1 docker container and want to have dockers IP same as your host, start the docker container using --net=host flag to set the container to have the host machine IP address.

Other way is to have these options configured at server startup(by editing DOCKER_OPTS in /etc/default/docker): --bip=CIDR — to supply a specific IP address and netmask for the "docker0" bridge, using standard notation like 192.168.1.8/23. For example with --fixed-cidr=192.168.1.0/25, IPs for your containers will be chosen from the first half of 192.168.1.0/24 subnet. The "docker0" Ethernet bridge settings are used every time you create a new container. You are trying to bind a container's ports to a specific port using the -p flag , which will not help you in assigning a IP address to the container.

Another way to assign a IP address in any particular range(Example: 172.30.1.21/30). Stop the docker using stop docker , then use ip link and ip addr commands to set up the "bridge br0" and start docker using docker -d -b br0



标签: docker