Manage Ports in Docker
The Docker containers run services inside it on a specific port. To access that services of container running on a port, You need to bind container port with some Docker host port.
Have a look at below image. You will see that docker host is running two containers, one is running Apache which has some website and other have MySQL.
Now, you need to access the website running on Apache container on port 80. Let’s bind docker host port 8080 to containers port 80. You can also use port 80 on docker host as well.
The second container has MySQL running on port 3306. There are other ways to access MySQL from the host machine. But for this tutorial, I have bind docker host port 6603 to containers port 3306. Now you can directly access MySQL from Docker container by connecting host machine on port 6603.
The following commands will bind host system port with containers port.
$ docker run -it -p 8080:80 apache_image $ docker run -it -p 6603:3066 mysql_image
In the second example use our sample project available on Github. This will show you a running example of port binding. Just clone the repository using the following command.
$ git clone https://github.com/tecrahul/dockerfile $ cd dockerfile
Now build the docker image with name apacheimage.
$ docker build -t apacheimage .
Now run the container using docker run command. The Apache service will start on the container on port 80. You need to specify -p 8080:80 to bind host system port 8080 with container port 80.
$ docker run -it -p 8080:80 apacheimage
Now access host machine IP with port 8080 in the web browser. You will get a page running on container’s Apache service like below. My host machine IP is 192.168.1.237.
You can bind multiple ports as well with a single container, but make sure to EXPOSE all ports in Dockerfile before building the image.
$ docker run -it -p 8080:80,8081:443 image_name
If you need to bind port with the specific interface of host machine define its IP address as below. The below example, port 8080, 8081 will accessible with 127.0.0.1 IP only.
$ docker run -it -p 127.0.0.1:8080:80,127.0.0.1:8081:443 image_name $ docker run -it -p 192.168.1.111:8080:80,188.8.131.52:8081:443 image_name