Port and Volume Mapping

In this section, we will learn how to map a port inside a docker container to a port of the docker host. More importantly, we will see how to have persistent storage.

  1. Introduction
  2. Docker File
  3. Basic Docker Commands
  4. Port and Volume Mapping (You are here!)
  5. Docker Networking
  6. Docker Storage
  7. Docker Compose
  8. Deleting Docker Entities

To map a port on a host to a container we need to use the -p flag of the docker run command.

docker run -p <port_number_on_host>:<port_number_on_container> <image>

The following command will run a container for mlflow and map port 7000 of this container to port 7000 of the docker host.

docker run -p 7000:7000 mlflow

Similarly, the following command will run a container for postgresql and map port 5432 of this container to port 5432 of the docker host.

docker run -p 5432:5432 postgresql

The only important thing to note is that due to many to one association of containers and the host, once a service is already running on a port on the host we can not map another container to that port. Hence, in order to run another instance of postgresql on the host, we have to choose a port that is not in use.

docker run -p 1234:5432 postgresql

We can similarly map a volume or a location on the host to a location inside the container for persistent storage.

docker run -v <location_on_host>:<location_on_container> <image>

The following command will run an instance of postgresql and map /opt/db on the docker host to /home/db inside the container.

docker run -v /opt/db:/home/db postgresql

In the next section, we will learn about Docker Networking!

Reference:

[1] Mumshad Mannambeth, Docker for the Absolute Beginners (2020), KodeKloud.com

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sumeet Gyanchandani

Sumeet Gyanchandani

84 Followers

Machine Learning Engineer at Unit8 | Former Thesis Intern at Microsoft Research | Master of Science in Artificial Intelligence