我正在尝试将我的应用程序连接到Redis,但我得到:
[ioredis] Unhandled error event: Error: connect ECONNREFUSED 127.0.0.1:6379
当我做:
docker exec -it ed02b7e19810 ping test_redis_1 我已经收到所有数据包。
docker exec -it ed02b7e19810 ping test_redis_1
Redis容器也声明:
* Running mode=standalone, port=6379
* Ready to accept connections
(我得到警告,但我不认为与之相关:
Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128
这是我的docker-compose.yaml:
version: '3' services: test-service: build: . volumes: - ./:/usr/test-service/ ports: - 5001:3000 depends_on: - redis redis: image: "redis:alpine"
Docker文件
FROM node:8.11.2-alpine WORKDIR /usr/test-service/ COPY . /usr/test-service/ RUN yarn install EXPOSE 3000 CMD ["yarn", "run", "start"]
app.js
const Redis = require('ioredis'); const redis = new Redis(); redis.set('foo', 'bar'); redis.get('foo').then(function (result) { console.log(result); });
我也尝试过redis包装,但仍然无法连接:
redis
var redis = require("redis"), client = redis.createClient(); client.on("error", function (err) { console.log("Error " + err); });
得到:
Error Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379
对于该特定项docker-compose.yml,没有redison 127.0.0.1,您应该将其redis用作主机,因为同一Docker网络上的服务能够使用服务名称作为DNS来找到彼此。
docker-compose.yml
127.0.0.1
const Redis = require('ioredis'); const redis = new Redis({ host: 'redis' });
此外,depends_on 不等待redis容器在启动之前就准备好,它只会首先启动它,因此在启动之前等待app.js或只是在内部处理它是您的工作app.js
depends_on
io-redis带有重新连接策略,因此您可能需要先尝试一下。
io-redis