Publishing a container's port - the -p option

Docker enables you to publish a service offered inside a container by binding the container's port to the host interface. The -p option of the docker run subcommand enables you to bind a container port to a user-specified or autogenerated port of the Docker host. Thus, any communication destined for the IP address and the port of the Docker host will be forwarded to the port of the container. The -p option, actually, supports the following four formats of arguments:

  • <hostPort>:<containerPort>
  • <containerPort>
  • <ip>:<hostPort>:<containerPort>
  • <ip>::<containerPort>

Here, <ip> is the IP address of the Docker host, <hostPort> is the Docker host port number, and <containerPort> is the port number of the container. Here, in this section, we present you with the -p <hostPort>:<containerPort> format and introduce other formats in the succeeding sections.

In order to understand the port binding process better, let's reuse the apache2 HTTP server image that we crafted previously and spin up a container using a -p option of the docker run subcommand. The 80 port is the published port of the HTTP service, and as the default behavior, our apache2 HTTP server is also available on port 80. Here, in order to demonstrate this capability, we are going to bind port 80 of the container to port 80 of the Docker host, using the -p <hostPort>:<containerPort> option of the docker run subcommand, as shown in the following command:

$ sudo docker run -d -p 80:80 apache2
baddba8afa98725ec85ad953557cd0614b4d0254f45436f9cb440f3f9eeae134

Now that we have successfully launched the container, we can connect to our HTTP server using any web browser from any external system (provided it has a network connectivity) to reach our Docker host.

So far, we have not added any web pages to our apache2 HTTP server image. Hence, when we connect from a web browser, we will get the following screen, which is nothing but the default page that comes along with the Ubuntu Apache2 package:

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

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