How to access localhost from docker container?

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'
services:
  web:
    build: .
    ports:
      - '80:80'
    extra_hosts:
      - "localhost:192.168.2.XX"

Notice following line:

extra_hosts:
  - "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"