Docker Port Mappings and Hostnames

Viewed 22220

I have got an question, or better to say there are two ones. Both depends on Docker and is related to the understanding of how docker deals with containers hostnames and ports.

Let's say I have two services that are running in a different docker container and exposing port 80 from the container to port 8081 (service1) and port 8082 (service2):

service1 : 8081 : 80 service2: 8082 : 80

Now it is clear to me that from an host perspective I can access these services by using the exposed ports (http://localhost:8081 and http://localhost:8082). But what if I want to access my services by using the containers like http://container1 and http://container2? What I have to do to realize this szenario meaning:

  • how might be the port forwarding
  • and how I know the exact hostname so I could resolve the containers hostnames from the docker host machine?

Thanks for help!

1 Answers

As Ijaz Ahmad Khan said. You have to use another container inside that network as proxy eg nginx.

If you are exposing ports from docker-compose to host machine ( your pc ) it's only visible as localhost domain with specific port as you mention. If you run docker-compose.yml like this:

version: "3"
services:
  service1:
    image: something
    name: service1_name
    ports:
      - "8081:80"
  service2:
    image: something
    name: service2_name
    ports:
      - "8082:80"

Docker-compose will create default network named by folder in witch is docker-compose.yml with suffix _default. In this network all container can see each other. expose command is used for containers inside this network (so they can see each other and communicate), port is used for publishing to host-machine (your pc). This mean:

service1 is visible on your machine as http://localhost:8081 for others containers in the network as service1:80.

service2 is visible on your machine as http://localhost:8082 for others containers in the network as service2:80.

See that specified container name doesn't have effect on service network address. To test that containers are only visible inside the network try to ping them from another container

docker run --rm --network=your_folder_name_default debian ping service1

To check in which network your containers are running you could use inspect

docker inspect service1_name

Now you have to use the container name

Related