'"Error: Connection timeout" when connecting to Redis Docker instance
I'm running my Node/Express app inside a Docker container, joined together with a Redis instance through Docker Compose. The problem is, when I try to connect the Node app with Redis (using this npm package, v^4.0.1), I get this error:
Error: Connection timeout
at Socket.<anonymous> (/app/node_modules/@node-redis/client/dist/lib/client/socket.js:163:124)
at Object.onceWrapper (node:events:509:28)
at Socket.emit (node:events:390:28)
at Socket.emit (node:domain:537:15)
at Socket._onTimeout (node:net:501:8)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7)
If I run a separate Redis instance with docker run --name my-redis -p 6379:6379 -d redis and I use 127.0.0.1:6379 as the connection URL in Node it works. So I think it's something about Docker networking, but I can't find what.
This is my docker-compose.yaml:
version: "3.9"
services:
api:
build: .
volumes:
- ./src/:/app/src/
ports:
- "8080:8080"
environment:
- NODE_ENV
redis:
image: "redis:6.2.6"
This is the Dockerfile for the Node app:
# base image
FROM node:16.13.0-alpine
# working directory
WORKDIR /app
# add binaries to $PATH
ENV PATH /app/node_modules/.bin:$PATH
# install and cache app dependencies
COPY package*.json ./
RUN npm install
# copy app files and build
COPY . .
RUN npm run build
# start app
CMD [ "npm", "start", "--ENV=${NODE_ENV}" ]
And this is the code I use for connecting to Redis in my Node app:
import { createClient } from "redis";
(...)
const client = createClient({ url: `redis://redis:6379` });
client.on("error", (error) => {
throw error;
});
await client.connect();
const data = await client.get(customerId);
await client.quit();
return data;
Any help, please?
Thank you very much!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
