我正在努力将Redis部署连接到我的nodejs应用程序。当然,在本地不使用docker的情况下,它可以很好地工作,所以我对于这是否与我的代码有关,还是与我设置docker compose文件有关的方式存有争议
Dockerfile:
FROM node:8
WORKDIR /app
COPY package.json /app
COPY . /app
RUN npm install
CMD ["npm", "start"]
EXPOSE 3000
docker-compose.yml
version: "3"
services:
web:
container_name: web-container
restart: always
depends_on:
- redis
build: .
ports:
- "3000:3000"
links:
- redis
redis:
container_name: redis-container
image: "redis:latest"
ports:
- "6379:6379"
volumes:
- ./data:/data
Redis连接文件(RedisService.js)
const redis = require("redis");
const client = redis.createClient();
const DbUtils = require("../../db_utils");
const {promisify} = require("util");
const getAsync = promisify(client.get).bind(client);
const existsAsync = promisify(client.exists).bind(client);
class RedisCache {
constructor () {
var connected;
// * Initiliase the connection to redis server
client.on("connect", () => {console.log("? Redis cache is ready"); connected = true;})
client.on("error", (e) => {console.log("Redis cache error:\n" + e); connected = false;});
}
async setData (id, data) {
// * Stringify data if it's an object
data = data instanceof Object ? JSON.stringify(data) : data;
client.set(id, data);
return true;
}
async getData (key) {
return getAsync(key).then(data => {
data = JSON.parse(data) instanceof Object ? JSON.parse(data) : data;
return data;
})
}
async exists (key) {
return existsAsync(key).then(bool => {
return bool;
})
}
// Returns status of redis cache
async getStatus () {
return this.connected;
}
}
module.exports = new RedisCache();
错误 错误:Redis与127.0.0.11:6379的连接失败-连接ECONNREFUSED 127.0.0.11:6379
答案 0 :(得分:1)
通过docker-compose
运行容器时,它们都已连接到公共网络。服务名称是给定容器的DNS名称,因此要从redis
访问web
容器,您应该像这样创建客户端:
const client = redis.createClient({
port : 6379,
host : 'redis'
});
您尚未配置主机,因此它使用默认主机-127.0.0.1
。但是从您的web
容器的角度来看,redis不在本地主机上运行。相反,它在自己的容器中运行,该容器的DNS名称为redis
。