Practical Use Cases and Examples
Running a Web Server
Suppose you have a web application running in a Docker container that listens on port 80
inside the container. To make the application accessible from the host machine, you can map the container's port 80
to a custom port on the host, such as 8080
:
docker run -p 8080:80 my-web-app
Now, you can access the web application by visiting http://localhost:8080
on the host machine.
Exposing a Database Server
If you have a database server (e.g., MySQL) running in a Docker container, you can map the container's database port (e.g., 3306
) to a custom port on the host:
docker run -p 3306:3306 mysql
This will allow other applications running on the host machine to connect to the MySQL database server inside the container using the host's port 3306
.
Mapping Multiple Ports
In a more complex scenario, you might have a multi-tier application where different components (e.g., web server, application server, database) run in separate Docker containers. You can map multiple ports to expose these components:
docker run -p 8080:80 -p 8000:8000 -p 3306:3306 my-app
This will map the host's port 8080
to the container's port 80
(web server), the host's port 8000
to the container's port 8000
(application server), and the host's port 3306
to the container's port 3306
(database server).
Using Random Port Mapping
If you don't want to specify a specific port on the host machine, you can let Docker automatically assign an available port:
docker run -p 80 my-web-app
In this case, Docker will map the container's port 80
to an available port on the host machine. You can use the docker ps
command to see the assigned port.
By understanding these practical use cases and examples, you can effectively leverage Docker's port mapping capabilities to expose your containerized applications and services to the outside world, enabling seamless communication and access to your applications.