How to Expose Multiple Containers On the Same Port
First off, why you may need it:
- Load Balancing - more containers mean more capacity
- Redundancy - if one container dies, there won't be downtime
- Single Facade - run multiple apps behind one frontend
Interested? Read on!🔽
Docker doesn't support binding multiple containers to the same host port.
Instead, it suggests using an extra container with a reverse proxy like Nginx, HAProxy, or Traefik.
Here are two ways you can trick Docker and avoid adding the reverse proxy:
1. SO_REUSEPORT 2. iptables
Multiple Containers On the Same Port w/o Proxy (I)
1) Use SO_REUSEPORT sockopt for your server sockets 2) Run containers with `--network host` and the same port
SO_REUSEPORT allows binding diff processes to the same port.
--network host puts all containers on one network stack.
Containers are Virtual Machines (controversial thread)
Some mental gymnastics. Bear with me.
Person A comes to Containers with prior VM experience.
Dockerfiles start FROM debian/centos/etc.
docker run/exec feels like SSH-ing sessions into servers.
Containers are VMs!
A container starts in less than a second
A VM takes tens of seconds to start
A bare-metal server can run hundreds of containers
Only a few VMs can coexist on a server
How come?
Person A starts digging into the internals to understand the difference between containers and VMs.
Person A: Aha! Containers are just isolated and restricted Linux processes + OS-level virtualization!
Person A starts sharing the finding with friends and colleagues - seasoned backend devs. Everyone instantly grasps the idea.
Then a Person B comes by. W/o prior VM experience.
- What is Kubernetes Service?
- When to use ClusterIP, NodePort, or LoadBalancer?
- How does multi-cluster service work?
- Why both Ingress and Ingress Controller?
The answers become clear when things are explained bottom-up! 🔽
1. Low-level Kubernetes Networking Guarantees
To make Pods mimicking traditional VMs, Kubernetes defines its networking model as follows:
- Every Pod gets its own IP address
- Pods talk to other Pods directly (no visible sNAT)
- Containers in a pod communicate via localhost
2. Kubernetes does nothing for low-level networking!
It delegates the implementation to Container Runtimes and networking plugins.
A typical example: cri-o (CR) connects pods on a node to a shared Linux bridge; flannel (plugin) puts nodes into an overlay network.