Home > other >  How do server programs work on Docker when *only* the listening port is mapped to the Docker host?
How do server programs work on Docker when *only* the listening port is mapped to the Docker host?

Time:08-04

This is just a conceptual question that I have been thinking about recently.

Say I'm running an Nginx container on Docker on a host. Normally, for this to work, we have to map ports like 80 and 443 to host container. This is because these are listening ports, and connections from the outside world to port 80 should be forwarded to port 80 of the container. So far so good.

But also: port 80 is just the listening socket, right? The listening socket only accepts the connection; after this any communication done between a client and the Nginx server is supposedly done on a different socket with a random port number (on the server side). This is to allow multiple connections, and to keep the listening port free to establish more connections, etc. This is where my issue comes in.

Say I'm a client and I connect to this Nginx server. As far as I understand, I first send TCP packets to port 80 of the host that is hosting this Nginx Docker container. But during the establishment of the connection, the server changes their port to another number, say 45670. (Not sure how, but I am guessing the packets that are sent back suddenly mention this port, and our client will continue the rest of the exchange with this port number instead). But now as I send packets (e.g. HTTP requests) to the host on port 45670, how will the Nginx docker container see those packets?

I am struggling to understand how server processes can run on Docker with only one port exposed / published for mapping.

Thanks!

CodePudding user response:

But also: port 80 is just the listening socket, right? The listening socket only accepts the connection; after this any communication done between a client and the Nginx server is supposedly done on a different socket with a random port number (on the server side).

Nope. When a connection is established, the client side is a random port number (usually) and the server side is the same port that the server listens on.

In TCP there aren't actually listening sockets - they're an operating system thing - and a connection is identified by the combination of both the port numbers and both the IP addresses. The client sends a SYN ("new connection please") from its port 49621 (for example) to port 80 on the server; the server sends a SYN/ACK ("okay") from its port 80 to port 49621 on the client.

  • Related