Search code examples
dockerdocker-composesveltekit

Docker-compose: Sveltekit app not able to connect to redis


When I run docker compose up, the app instance is getting an error of

[ioredis] Unhandled error event: Error: connect ECONNREFUSED 127.0.0.1:6379

Here's the docker-compose.yaml:

services:
  app:
    restart: always
    image: svelte-docker
    build:
      context: .
      dockerfile: Dockerfile
      target: run
    ports:
      - 5173:5173
    networks:
      - net-a
  cache:
    image: redis:alpine
    restart: always
    ports:
    - 6379:6379
    networks:
      - net-a
networks:
  net-a:
    driver: bridge

Within the app I'm using the generic protocol connector:

const redis = new Redis({
    url: 'redis://redis:6379'
});

If I run the app outside of docker, with a running redis instance inside docker, they talk to each other just fine. But when I try to put both inside a compose file, they can't.

What am I doing wrong here?


Solution

  • When you use Docker Compose like that, you should see it as each of your services will run on their own computers. So in your app service, you can't use redis://redis:6379 to connect to the Redis database.

    But, when you use Docker Compose like this, then each service computer will register domain names to the other services, which we can use to connect establish connections between them. The names are the same names as you have given your services. So in your app service, you can use the domain name cache to refer to the computer that runs your Redis database.