Manage Ports in Docker

Manage Ports in Docker

 Manage Ports in Docker


The Docker containers run services inside it on a specific port. To access that services of the container running on a port, You need to bind the container port with some Docker host port.

Example 1

Have a look at the below image. You will see that the Docker host is running two containers, one is running Apache which has some websites and the other has 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 the 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 bound docker host port 6603 to containers port 3306. Now you can directly access MySQL from Docker container by connecting the host machine to port 6603.

The following commands will bind the host system port with the containers port.

$ docker run -it -p 8080:80 apache_image
$ docker run -it -p 6603:3066 mysql_image

Example 2

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 the name apache image.

$ docker build -t apacheimage .

Now run the container using the 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 the host machine IP with port 8080 in the web browser. You will get a page running on the container’s Apache service like below. My host machine IP is 192.168.1.237.

More Examples

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 the host machine define its IP address as below. The below example, port 8080, 8081 will be 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,92.168.1.111:8081:443 image_name
Reactions

Post a Comment

0 Comments

close