0

i'm running a node.js application in a docker container. Here is my docker-compose file -

version: '3.7'
services:
  notification-app:
    container_name: ${CONTAINER_NAME}
    build:
      context: ./
      dockerfile: ./Dockerfile
      args:
        - APP_ENV=${APP_ENV}
    ports:
      - ${EXPORTED_PORT}:${APP_PORT}
    environment:
      - REDIS_HOST=${REDIS_HOST}
      - REDIS_PORT=${REDIS_PORT}

And here is my .env file -

CONTAINER_NAME=sheba_socket

APP_ENV=development
APP_PORT=3000
EXPORTED_PORT=3000

REDIS_HOST=localhost
REDIS_PORT=6379

I'm running a REDIS SERVER locally (No container, directly on machine). When i built and run this container, i found this error.

[ioredis] Unhandled error event: Error: getaddrinfo ENOTFOUND redis
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:64:26)

I think, the problem is here REDIS_HOST=localhost. I am not sure how to define redis host.

Hasan Hafiz Pasha
  • 1,402
  • 2
  • 17
  • 25

2 Answers2

2

If you use Docker for Mac or Docker for Windows, your containers are not running on your host but in a little VM. If you want to have a container to connect into one of your host service, you can use this address instead of localhost: host.docker.internal

On your host, you need to bind your service on 0.0.0.0 or other IP but not 127.0.0.1.

jmaitrehenry
  • 2,190
  • 21
  • 31
2

You can run your notification-app service on host network using network_mode: "host"

Updated docker-compose.yml:

version: '3.7'
services:
  notification-app:
    container_name: ${CONTAINER_NAME}
    build:
      context: ./
      dockerfile: ./Dockerfile
      args:
        - APP_ENV=${APP_ENV}
    environment:
      - REDIS_HOST=${REDIS_HOST}
      - REDIS_PORT=${REDIS_PORT}
    network_mode: "host"     //Here is the change

You may have noticed that I had removed the ports from the original docker-compose file. This is because when we run a service on the host network, the service binds directly to the port on the Docker host. Hence no need to expose the port in host network.

With this change, you're not required to update the .env file.

REDIS_HOST=localhost would work fine.

Read more about docker host networking here

Noam Yizraeli
  • 4,446
  • 18
  • 35
Kapil Khandelwal
  • 1,096
  • 12
  • 19
  • (This generally completely disables Docker's networking setup. You will not have isolation from host processes or the outside network, and "normal" inter-container communication using containers' names as DNS names will not work.) – David Maze Apr 23 '20 at 18:48