2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

「Redis Client Error AggregateError [ECONNREFUSED]」の解決方法【Docker Compose】

2
Posted at

はじめに

Redisを使ったアプリをDockerで動かそうとしたらエラーが発生しました。

問題

エラー内容

api       |Redis Client Error AggregateError [ECONNREFUSED]: 
api       |     at internalConnectMultiple (node:net:1135:18)
api       |     at afterConnectMultiple (node:net:1716:7) {
api       |   code: 'ECONNREFUSED',
api       |   [errors]: [
api       |     Error: connect ECONNREFUSED ::1:6379
api       |         at createConnectionError (node:net:1679:14)
api       |         at afterConnectMultiple (node:net:1709:16) {
api       |       errno: -111,
api       |       code: 'ECONNREFUSED',
api       |       syscall: 'connect',
api       |       address: '::1',
api       |       port: 6379
api       |     },
api       |     Error: connect ECONNREFUSED 127.0.0.1:6379
api       |         at createConnectionError (node:net:1679:14)
api       |         at afterConnectMultiple (node:net:1709:16) {
api       |       errno: -111,
api       |       code: 'ECONNREFUSED',
api       |       syscall: 'connect',
api       |       address: '127.0.0.1',
api       |       port: 6379
api       |     }
api       |   ]
api       | }

元のコード

backend/src/redisClient.ts
import { createClient } from "redis";

export const client = createClient();

client.on("error", (err) => console.log("Redis Client Error", err));

await client.connect();

解決方法

Redisのコンテナ内のポート6379にバックエンドのコンテナ内から接続できるようにコンテナのサービス名でURLを指定しました。
(バックエンドから見たlocalhost:6379はバックエンドのコンテナ内のlocalhost:6379だからです。実際はRedisのコンテナのlocalhost:6379に接続したいです。)

backend/src/redisClient.ts
import { createClient } from "redis";

export const client = createClient({
  url: process.env.REDIS_URL,
});

client.on("error", (err) => console.log("Redis Client Error", err));

await client.connect();
docker-compose.yml
version: "3.8"
services:
  client:
    build: ./frontend
    container_name: frontend
    ports:
      - "5173:5173"
    depends_on:
      - api
    volumes:
      - ./frontend:/app
      - /app/node_modules

  api:
    build: ./backend
    container_name: api
    ports:
      - "3000:3000"
    environment:
      REDIS_URL: redis://redis:6379
    depends_on:
      - redis
    volumes:
      - ./backend:/app
      - /app/node_modules

  redis:
    image: redis:latest
    container_name: my-redis
    ports:
      - "6379:6379"

おわりに

バックエンドを自分のPCのローカルで立ち上げていた時は、URLを指定しなくてもRedisに接続できていました。指定しないと勝手にlocalhost:6379に接続されるようです。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?