我正在努力将 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
最佳答案
当您通过 docker-compose 运行容器时,它们都连接到一个公共(public)网络。服务名称是给定容器的 DNS 名称,因此要从 web
访问 redis
容器,您应该创建客户端,如下所示:
const client = redis.createClient({
port : 6379,
host : 'redis'
});
您尚未配置主机,因此它使用默认主机 - 127.0.0.1
。但从 web
容器的 Angular 来看,redis 并未在本地主机上运行。相反,它在自己的容器中运行,DNS 名称为 redis
。
关于javascript - 无法将Redis服务器连接到nodejs,Docker compose,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59448292/