skip to Main Content

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.

2

Answers


  1. 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.

    Login or Signup to reply.
  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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search