I try to connect to Redis from my backend, but I keep getting the following error:
...
api-1 | [ioredis] Unhandled error event: Error: getaddrinfo ENOTFOUND undefined
api-1 | at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:71:26)
api-1 | [ioredis] Unhandled error event: Error: getaddrinfo ENOTFOUND undefined
api-1 | at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:71:26)
...
Here is how I config my redis client:
import Redis from "ioredis";
export const redisConfig = () => {
if (process.env.NODE_ENV === "production") {
return `redis://${process.env.REDIS_HOST}:${process.env.REDIS_PORT}`;
}
return "";
};
const redisCli = new Redis(redisConfig());
export default redisCli;
And this is my dockerfile:
# ---- Dependencies ----
FROM node:16-alpine AS base
# minimize image size
RUN apk add --no-cache libc6-compat
RUN npm install -g npm@latest
WORKDIR /app
COPY ./package*.json ./
RUN npm ci
# ---- Builder ----
FROM node:16-alpine AS builder
RUN npm install -g npm@latest
WORKDIR /app
COPY --from=base /app/node_modules ./node_modules
COPY ./src ./src
COPY package*.json tsconfig.json webpack.config.ts ./
RUN npm run build
# ---- Release ----
FROM node:16 AS release
WORKDIR /app
# COPY ./prisma ./prisma
# COPY ./.env ./
# COPY ./deployment ./deployment
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./
# RUN npx prisma generate
RUN npm install pm2 -g
EXPOSE 3000
This one is the docker-compose.yml:
version: "3"
services:
api:
build: ./
depends_on:
- redis
links:
- redis
command: sh -c "node dist/server.js"
environment:
- REDIS_HOST=redis
- REDIS_PORT=6379
- NODE_ENV=production
ports:
- 3000:3000
redis:
image: "redis:latest"
I have specified the links in docker-compose, but still receiving the same error.
How can I fix the error? Thanks for any help!!
2
Answers
You are receiving this error because your application is probably trying to connect to redis before redis is up and accessible. In your
depends_on
section, you can say that you want to start your application after your redis service is healthy. To do so, you must also configure a healthcheck to tell when redis is really ready to accept connections (redis-cli ping
for example).Here is an example of configuration that works for me:
Was able to connect with such a config into the Redis hosted in Docker
where 49155 is the doker path port