Saturday, February 8, 2020

What is Docker port mapping explained

In the realm of Docker, where your applications reside within isolated containers, port mapping is the bridge that connects these containers to the outside world. It's like opening a door in your container's firewall, allowing specific types of network traffic (like web requests) to pass through.

Port mapping is a fundamental concept in Docker that unlocks the potential of any containerised applications. By understanding how it works, we can seamlessly expose the applications to the world and build powerful, interconnected systems.

Why Do We Need It?
Let's say we've built a web application inside a Docker container. By default, this application is only accessible within the container. Port mapping lets us expose a port within the container to our host machine (local computer), so anyone on the network can interact with containerised application.

How Does it Work?
Container Ports: Application inside the container listens on a specific port. This is often port 80 for web servers or 3306 for databases.

Host Ports: We need to choose a port on the host machine that we want to map to the container port. This can be the same port number or a different one.

The -p Flag: When you run your Docker container, you use the -p flag to establish this mapping. It looks like this:

docker run -p <host_port>:<container_port> <image_name>

<host_port>: The port on your host machine.

<container_port>: The port your application is listening on inside the container.

<image_name>: The name of your Docker image.


Putting this all together:
Let's say we have a basic web server running on port 80 inside a container.
Run command Docker run -p 8080:80 my_web_server_image

This command maps port 8080 on the host machine to port 80 inside the container.
Now, we can access the web application by opening a browser and going to http://localhost:8080.

Key things to Remember:
- We can map multiple ports at once using multiple -p flags.
- If we don't specify a host port (e.g., -p 80), Docker will automatically assign a random available port on the host.
- Port mapping is crucial for making the containerised applications accessible and useful.
- When a port is mapped, it's considered "published" and listed in the docker ps output.
- Be mindful of port conflicts on your host machine. If another application is already using a port, you'll need to choose a different one for your container, otherwise the app wont be accessible as it should
- Docker networking offers more advanced ways to control how containers communicate with each other and the outside world.

Happy Dockering!

No comments:

Post a Comment