skip to Main Content

I am trying to connect with redis(of docker instance) using express(node.js).
Here is my index.ts file in which i am trying to connect with redis

import mongoose from 'mongoose'
import express from 'express'
import session from 'express-session'
import connectRedis from 'connect-redis'
import Redis from 'ioredis'
import { MONGO_URI, MONGO_OPTIONS, REDIS_OPTIONS, APP_PORT } from './config'
import { createApp } from './app';

; (async () => {
    await mongoose.connect(MONGO_URI, MONGO_OPTIONS)

    const RedistStore = connectRedis(session)

    const client = new Redis(REDIS_OPTIONS)

    const store = new RedistStore({ client })

    const app = createApp(store)

    app.listen(APP_PORT, () => console.log('server running on port 3000'))
})()

Here is my REDIS_OPTIONS file in which i have all redis options.

import { RedisOptions } from 'ioredis'

const {
    REDIS_PORT = 6379,
    REDIS_HOST = 'localhost',
    REDIS_PASSWORD = 'secret'
} = process.env

export const REDIS_OPTIONS: RedisOptions = {
    port: +REDIS_PORT,
    host: REDIS_HOST,
    password: REDIS_PASSWORD
}

docker-compose.yml

version: '3'

services: 
  db:
    user: $UID
    image: mongo
    ports:
    - '27017:27017'
    environment:
      MONGO_INITDB_ROOT: ''
      MONGO_INITDB_PASSWORD: ''
      MONGO_INITDB_DATABASE: auth,
      MONGO_USERNAME: ''
      MONGO_PASSWORD: ''
    volumes:
      - ./data:/data/db
      - ./mongo-init.sh:/docker-entrypoint-initdb.d/mongo-init.sh:ro
  
  cache: 
    image: redis:alpine
    ports: 
      - '6379:6379'
    command: ['--requirepass "secret"']
      

package.json

{
    "name": "node-auth",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "up": "docker-compose up -d",
        "postup": "npm run dev",
        "stop": "docker-compose stop",
        "down": "docker-compose down",
        "dev": "npm run dev --prefix api"
    },
    "keywords": [],
    "author": "",
    "license": "ISC"
}

Now when i try to run my main app file so i am getting this error

[ioredis] Unhandled error event: Error: connect ECONNREFUSED 127.0.0.1:6379 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1106:14) node.js

How can i get rid of this error?

2

Answers


  1. Looks like it might be a problem with the Redis container. What command you used to run the container? Try adding -p 6379:6379 with your docker command. Also, check whether port 6379 is used by something else or blocked by antivirus or firewall.

    Login or Signup to reply.
  2. change host in index.ts from ‘localhost’ to ‘redis’

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