Binding a container to a specific IP address

Until now, with the method that you learned, the containers always get bound to all the IP addresses configured on the Docker host. However, you may want to offer different services on different IP addresses. In other words, a specific IP address and port would be configured to offer a particular service. We can achieve this in Docker using the -p <ip>:<hostPort>:<containerPort> option of the docker run subcommand, as shown in the following example:

$ sudo docker run -d -p 198.51.100.73:80:80 apache2
92f107537bebd48e8917ea4f4788bf3f57064c8c996fc23ea0fd8ea49b4f3335

Here, the IP address must be a valid IP address on the Docker host. If the specified IP address is not a valid IP address on the Docker host, the container launch will fail with an error message, as follows:

2014/11/09 10:22:10 Error response from daemon: Cannot start container 
99db8d30b284c0a0826d68044c42c370875d2c3cad0b87001b858ba78e9de53b:
Error starting user land proxy: listen tcp 10.110.73.34:49153: bind:cannot assign requested address

Now, let's quickly review the port mapping as well the NAT entry for the preceding example:

  • The following text is an excerpt from the output of the docker ps subcommand that shows the details of this container:
      92f107537beb        apache2:latest      "/usr/sbin/apache2ct   
About a minute ago Up About a minute 198.51.100.73:80->80/tcp
boring_ptolemy
  • The following text is an excerpt from the output of the iptables -n nat -L -n command that shows the DNAT entry created for this container:
      DNAT    tcp -- 0.0.0.0/0      198.51.100.73     tcp dpt:80 
to:172.17.0.15:80

After reviewing both the output of the docker run subcommand and the DNAT entry of iptables, you will realize how elegantly the Docker Engine has configured the service offered by the container on the 198.51.100.73 IP address and 80 port of the Docker host.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset