TufanMeric
TufanMeric

Reputation: 63

How to get redis address from docker compose?

I'm trying to pass redis url to docker container but so far i couldn't get it to work. I did a little research and none of the answers worked for me.

version: '3.2'
services:
  redis:
    image: 'bitnami/redis:latest'
    container_name: redis
    hostname: redis
    expose:
      - 6379
    links:
      - api
  api:
    image: tufanmeric/api:latest
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    networks:
      - proxy
    environment:
      - REDIS_URL=redis
    depends_on:
      - redis
    deploy:
      mode: global
      labels:
        - 'traefik.port=3002'
        - 'traefik.frontend.rule=PathPrefix:/'
        - 'traefik.frontend.rule=Host:api.example.com'
        - 'traefik.docker.network=proxy'

networks:
  proxy:

Error: Redis connection to redis failed - connect ENOENT redis

Upvotes: 2

Views: 8164

Answers (1)

David Maze
David Maze

Reputation: 159910

You can only communicate between containers on the same Docker network. Docker Compose creates a default network for you, and absent any specific declaration your redis container is on that network. But you also declare a separate proxy network, and only attach the api container to that other network.

The single simplest solution to this is to delete all of the network: blocks everywhere and just use the default network Docker Compose creates for you. You may need to format the REDIS_URL variable as an actual URL, maybe like redis://redis:6379.

If you have a non-technical requirement to have separate networks, add - default to the networks listing for the api container.

You have a number of other settings in your docker-compose.yml that aren't especially useful. expose: does almost nothing at all, and is usually also provided in a Dockerfile. links: is an outdated way to make cross-container calls, and as you've declared it to make calls from Redis to your API server. hostname: has no effect outside the container itself and is usually totally unnecessary. container_name: does have some visible effects, but usually the container name Docker Compose picks is just fine.

This would leave you with:

version: '3.2'
services:
  redis:
    image: 'bitnami/redis:latest'
  api:
    image: tufanmeric/api:latest
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    environment:
      - REDIS_URL=redis://redis:6379
    depends_on:
      - redis
    deploy:
      mode: global
      labels:
        - 'traefik.port=3002'
        - 'traefik.frontend.rule=PathPrefix:/'
        - 'traefik.frontend.rule=Host:api.example.com'
        - 'traefik.docker.network=default'

Upvotes: 4

Related Questions