Search code examples
dockerdocker-composedocker-network

How do I connect to local machine from inside of docker container created by docker-compose?


I have a docker container that has been created using docker-compose. Here is the yml file.

version: "3"
services:
  redis:
    image: "redis"
  web:
    image: "myimage"
    ports:
      - "8000:8000"
    environment:
      REDIS_HOST: redis
    volumes:
      - .:/usr/src/app
    depends_on:
      - "redis"
    command: ["npm", "start"]

From this container my web app needs to connect to the local machine because my local machine is running another web app that my docker container's web app needs to access. How do I do this? The localhost's webapp is hosted on a different port (7777).

I have already seen From inside of a Docker container, how do I connect to the localhost of the machine?, and I got it to work using "extra_hosts" option, but I want to know if there is another way to do this?


Solution

  • Docker compose is just a utility for starting multiple Docker containers. Thus almost all things that apply to starting a container using docker run are the same for containers started with docker-compose.

    In particular, since you are on a MAC, there is a special DNS name inside the container that resolved to the host machine.

    Depending on the docker version that you have the DNS may be a slightly different.

    For Docker 18.03 and onward you can use host.docker.internal

    For and above Docker 17.06 use docker.for.mac.host.internal

    Below 17.06 use docker.for.mac.localhost

    Thus you can connect to the web app on the machine using <dns-name>:7777

    UPDATE:

    To avoid hard coding the value in the code, pass this DNS name as an env variable to the container.

    environment:
        REDIS_HOST: redis
        WEB_APP: host.docker.internal
    

    Inside the app, fetch the WEB_APP environment variable and use it to connect