Linked docker container isn't reachable over exposed port

I have a docker-compose.yml file with two containers:

containerA:
...
ports:
- "80:9000"

containerB:
...
links:
- containerA

What I was expecting is to have a containerA reachable over port 80 from containerB, but it's reachable only via port 9000. The 80 port in only visible from a host machine.

Is there a way to make container's containerA 9000 port reachable via 80 port for all containers it is linked to, not just the host machine?


Solution 1:

When you expose a port using the ports section of the docker compose file, you are specifying a host:container mapping, so it is expected that 9000 on the container will be reachable through 80 on the host only.

You can expose a port directly to other containers https://docs.docker.com/compose/yml/#expose, but you cannot specify the external port number, only the 9000 (not the 80).

Another option is to use the ambassador pattern where you have an "ambassador" that is the go between from a consumer to a provider https://docs.docker.com/articles/ambassador_pattern_linking/

So container B -> container A ambassador -> container A

You could expose port 80 on the ambassador, and then the ambassador could connect to container A's port 9000.

As you build out a more sophisticated infrastructure, you can get more creative with service registries, so containers are locating each other through a service registry rather than simple container links.

As a matter of good practice though, you generally shouldn't specify the external port directly. If you do and you try to run multiple copies of the container on the same docker host, you will get port conflicts. Or if you're running another container that tries to expose the same external port, you will also get port conflicts.