Summary
In the previous video, we learned about running a container and port mapping to access it via a web browser or the Curl tool. In this video, we will discuss container networking, IP addresses, and port mappings to avoid conflicts.
Limited IP Addresses
IP Version 4 address, which is represented by something dot something dot something dot something, has a limited number of IP addresses. Therefore, containers won’t have public IP addresses but instead have IP addresses for their services like web servers, database servers, or mail servers.
Port Mapping
Containers will expose services on a port-by-port basis, and we will be dealing with port numbers to avoid conflicts. To find out the port mapping, we can use <a class="wiki-link" href="/blog/en/kubernetes/should-a-docker-container-run-as-root-or-user">docker</a> ps
or <a class="wiki-link" href="/blog/en/kubernetes/can-docker-connect-to-database">docker</a> port
if we know the container ID.
For instance, by using the command <a class="wiki-link" href="/blog/en/kubernetes/how-do-i-connect-a-docker-bridged-container-to-the-outside-of-the-host">docker</a> port <container_id>
, we can find out the host port number for a container running on port 8000.
$ docker port 302d30 8000/tcp -> 0.0.0.0:8888
Assigning a Custom Port Number
We can assign a custom port number by specifying the -p
flag followed by the mapping. For example, <a class="wiki-link" href="/blog/en/kubernetes/how-to-use-local-docker-images-with-minikube">docker</a> <a class="wiki-link" href="/blog/en/kubernetes/how-to-run-minikube-in-a-virtual-machine-ubuntu-vm-vt-x-amd-v">run</a> -d -p 88:8000 <image_name>
will map the host port 88 to the container port 8000.
$ docker run -d -p 88:8000 <image_name>
We can verify the mapping by using the <a class="wiki-link" href="/blog/en/kubernetes/docker/convert-docker-compose-to-kubernetes">docker</a> ps
command.
$ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 302d30 <image_name> "python app.py" 1 minute ago Up 1 minute 0.0.0.0:8888->8000/tcp gracious_mendeleev
Finding the IP Address
We can find the IP address of a container using the <a class="wiki-link" href="/blog/en/building-microservices-with-docker-creating-a-product-service">docker</a> inspect
command with the format option.
$ docker inspect --format '{{ .NetworkSettings.IPAddress }}' <container_id>
$ docker inspect --format '{{ .NetworkSettings.IPAddress }}' 302d30 172.17.0.2
However, we should remember that containers shouldn’t have public IP addresses. Instead, we should use port mapping to access services.
Conclusion
In conclusion, we can publish a web server inside a docker container, make it public, and access it from different computers by being aware of port mapping, which port number to use when accessing the service and running few commands.