1

I use docker-compose to build an application consisting of multiple docker containers. Those containers communicate using the default bridge get some IP address on that private network and publish there services on those IP addresses.

From within the containers I can access other containers simply by their name.

If I want to access such a service from the host it is possible to simply access the internal IP address on the bridge. However the exact IP address for each service is not obvious and might change after a restart.

Is there a way to easily access a docker service by name from the host?

(Yes, exposing a port on localhost would be an alternative, but for debugging it would be much more convenient to access services directly through the bridge.)

michas
  • 25,361
  • 15
  • 76
  • 121
  • There are similar questions already answered: https://stackoverflow.com/questions/37242217/access-docker-container-from-host-using-containers-name https://stackoverflow.com/questions/35828487/docker-1-10-access-a-container-by-its-hostname-from-a-host-machine – Yaroslav Shabalin Mar 17 '18 at 23:16

1 Answers1

0

I never read such functionality in docker documentation. As you right when you restart container its IP changes but their name is same as assign at runtime.

I write a simple bash script which do the same task which are you looking for

"Is there a way to easily access a docker service by name from the host?"

#!/bin/bash

# suppose these are your container name test , test1 etc mention all the name in this array

declare -a container_list=('test' 'test1')

for container_name in ${container_list[@]}
do
   # getting container ip by container name
   container_ip=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $container_name)
   #UPDATE
   # delete old entry 
    sed -i "/$container_ip  $container_name/d" /etc/hosts
   #adding them in hosts etc/hosts file so now test will be accesible from host with out exposing any port
   sed -i "1s/^/$container_ip  $container_name\n/" /etc/hosts
done
Adiii
  • 54,482
  • 7
  • 145
  • 148