docker-publicacion-puertos

Port Publishing in Docker

  • 4 min

The port publication is a Docker networking technique that binds a specific port on the host machine with an internal container port, creating a tunnel that allows external traffic to breach the isolation.

By default, containers are hermetic bunkers. They can access the internet (to download updates), but nobody can get in.

Imagine you’ve downloaded the Nginx image. You’ve executed docker run nginx. Docker tells you the container is running. Everything seems perfect.

You open your browser, type localhost, hit Enter, and… “Can’t connect”. What happened? The answer lies in what we saw in the previous chapter: Isolation.

Today we’ll look at Port Publishing to manage how ports are exposed, allowing your services to be accessible from outside the container 👇.

The anatomy of the -p flag

To allow incoming traffic, we must explicitly tell Docker to connect a port on our machine (Host) with a container port.

This is done with the -p (lowercase) flag, and the syntax is:

-p <HOST_PORT>:<CONTAINER_PORT>
Copied!

It’s always “from the outside in”. First comes MY computer (where I’m typing), then the CONTAINER.

Practical Example: The Web Server

Let’s imagine we launch an Nginx server. Internally, Nginx is configured by default to listen on port 80. That’s the container port (right side).

Now we need to decide which port on our PC (left side) we want to use.

We want to access it through port 8080 on our computer.

docker run -d -p 8080:80 nginx
Copied!
  • Access: We go to the browser and type localhost:8080.
  • Flow: Request hits my PC (8080) ➡️ Docker captures it ➡️ Sends it to the Container (80). It works! 👍

Restricting the IP

By default, when you do -p 8080:80, Docker publishes that port on all network interfaces of your computer (0.0.0.0).

This means that if you’re on a public WiFi network or in an office:

  1. You can access it via localhost:8080.
  2. Your colleague next to you can access it by using your IP 192.168.1.55:8080.

Sometimes we don’t want this. If you only want it to be accessible from YOUR computer (localhost) and no one else, you can specify the loopback IP:

docker run -d -p 127.0.0.1:8080:80 nginx