How to see a linked container as localhost?

7.9k Views Asked by At

I have these two containers:

api:
  image: social-learning
  ports:
    - "3000:3000"
  command: bundle exec rails s -p 3000 -b '0.0.0.0'
  volumes:
    - ../api:/app
  expose:
    - "3000"
web:
  image: social-learning-frontend
  ports:
    - "4200:4200"
    - "9000:9000"
  command: ember serve -p 4200
  volumes:
    - .:/app
  links:
    - api
  expose:
    - "3000"

When I do:

docker exec `docker ps -a | grep 'frontend_web_1' | awk '{print $1 }'` curl http://localhost:3000

I always get connection refused. I can access the other container through its IP but I'd prefer to do it as localhost.

Is it possible?

1

There are 1 best solutions below

5
On BEST ANSWER

There seems to be some confusion here.

It looks like you are trying to log into the web container and access the api container using the localhost address? This isn't going to work.

The best solution is just to use the link you've declared; within the web container you should be able to do curl http://api:3000. This works because Docker has added an entry to /etc/hosts for the api container for you.

Accessing via localhost will only work from the Docker host, where the container ports are published. I guess you could access the Docker host from within the container via the Docker bridge (e.g. curl 172.17.42.1:3000), but that seems pointlessly complicated and brittle.