Reputation: 1125
I am trying to connect to redis from node js in docker, but I am facing an error. Redis container starts successfully and I can ping with redis-cli. I think the problem might be somewhere else. The below code and configuration works on ubuntu 20.04, but shows error on arch linux (Docker version 20.10.17):
Redis Client Error Error: connect EHOSTUNREACH 172.18.0.2:6379
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1237:16) {
errno: -113,
code: 'EHOSTUNREACH',
syscall: 'connect',
address: '172.18.0.2',
port: 6379
}
Here is my docker compose file:
version: "3.7"
services:
app:
image: node:18.4-alpine
command: sh -c "yarn run dev"
ports:
- "4000:4000"
working_dir: /app
volumes:
- ./:/app
env_file:
- ./.env
redis:
image: redislabs/rejson:latest
ports:
- "6379:6379"
Here, I am trying to connect to redis from nodejs (node-redis 4.1.1):
const socket = {
host: "redis",
port: 6379
}
export const redisClient = createClient({
socket,
database: 0,
legacyMode: true
})
redisClient.on("error", (err) => {
console.log("Redis Client Error", err)
});
Upvotes: 1
Views: 1483
Reputation: 2919
This is probably a race condition. Can you add depends_on: redis
to your app
service? This will at least make sure that the redis
service is Running
before instantiating the application.
Also, it is good practice to add retry/wait loop in your application with a timeout for external connectivity for better resilience to such race condition problems. They are very common.
Upvotes: 1