I am simply connecting redis server from docker compose networks but its showing timeout error. I tried with localhost etc but its not working with that also. Here is my app.js
import express from "express";
import { createClient } from 'redis';
const app = express();
const port = process.env.PORT || 3000;
const apiPrefix = process.env.API_PRIFEX;
const client = await createClient(
{
url: 'redis://redis:6379'
})
on('error', err => console.log('Redis Client Error', err))
.connect();
client.set('visits', 0);
app.get("/", (req, res) => {
client.get('visits', (err, visits) => {
res.send("Number of visits is " + visits)
client.set('visits', parseInt(visits) + 1);
})
res.status(200).json({ success: true, message: "Server1 running." });
});
app.listen(port, () => {
console.log(service is up and running on Port:${port});
});
But the issue is that it shows: connect ECONNREFUSED 127.0.0.1:6379
My docker-compose.yml
looks like this I try with port and without port as well but nothing is working.
version: "3"
services:
redis:
image: "redis"
ports:
- "6379:6379"
node-app:
build: .
ports:
- "4001:3000"`
I have tried with different host name local host etc but in answers I have find I need to connect only with image name but still its not working.
2
Answers
The issue that you are encountering is that the address 127.0.0.1 in a docker container refers to itself, not to the host OS.
There are three ways you can solve that, both involve adding the
network
attribute:network_mode: host
. For more information refer to that answer from: Codestationredis
orredisdb
I hope that this was helpful for details check the documentation
docker-compose.yml
node-app
folder./node-app/Dockerfile
redis.conf
You can edit your files for this codes and files.