我正在尝试允许我的nodeJs docker镜像与我的redis docker镜像(Mac OS X环境)之间的通信: nodeJs Dockerfile: FROM node:4.7.0-slimEXPOSE 8100COPY . /nodeExpressDBCMD ["node", "nodeExpressDB/bin/www"] redis Dockerfile: F
nodeJs Dockerfile:
FROM node:4.7.0-slim EXPOSE 8100 COPY . /nodeExpressDB CMD ["node", "nodeExpressDB/bin/www"]
redis Dockerfile:
FROM ubuntu:14.04.3 EXPOSE 6379 RUN apt-get update && apt-get install -y redis-server
尝试连接到redis的nodeJs代码是:
var redis = require('redis'); var client = redis.createClient();
docker构建步骤:
docker build -t redis-docker . docker build -t node-docker .
docker run images步骤流程:
docker run -p 6379:6379 redis-docker docker run -p 8100:8100 node-docker
错误:
Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379 at Object.exports._errnoException (util.js:907:11) at exports._exceptionWithHostPort (util.js:930:20) at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1078:14)
我应该怎么做才能从node-docker连接到Redis?
Redis在一个单独的容器中运行,该容器具有单独的虚拟以太网适配器和运行节点应用程序的容器的IP地址.您需要为这两个容器提供 link或为它们创建一个 user defined networkdocker network create redis docker run -d --net "redis" --name redis redis docker run -d -p 8100:8100 --net "redis" --name node redis-node
然后在节点中连接时指定主机redis,以便redis客户端尝试连接到redis容器而不是默认的localhost
const redis = require('redis') const client = redis.createClient(6379, 'redis') client.on('connect', () => console.log('Connected to Redis') )
Docker Compose可以帮助定义多容器设置.
version: '2' services: node: build: . ports: - "8100:8100" networks: - redis redis: image: redis networks: - redis networks: redis: driver: bridge