How to access localhost from docker container?

Asked: a year ago

Sometime you want to access localhost from your docker container. If you ever want to do it you can use following method:

Using docker compose to connect to localhost

version: '2'
    build: .
      - '80:80'
      - "localhost:192.168.2.XX"

Notice following line:

  - "localhost:192.168.2.XX"

Extra hosts option is very useful to connect outside servie to docker container in this case we tell docker to connect to localhost via 192.168.2.XX ip address. This ip address is your host ip address. To find host ip address in mac os go to system preference > network.

Now if you login to your docker container and run curl http://localhost it will point to your host localhost. Alternatively, you can also use following command:

docker run --add-host="localhost:192.168.2.XX"
Viewed: 8144 times
Liked: 21 times