无法 link redis 容器到 docker 中的 node.js 容器

fail to link redis container to node.js container in docker

我在数字海洋云上部署了一个简单的基于 redis 的 nodejs 应用程序。

这是 node.js 应用程序。

var express = require('express');
var app = express();   
app.get('/', function(req, res){
  res.send('hello world');
});
app.set('trust proxy', 'loopback') 
app.listen(3000);

var redisClient = require('redis').createClient(6379,'localhost');
redisClient.on('connect',function(err){
   console.log('connect');
})

为了部署应用,我分别使用了一个node.js容器和一个redis容器,并将node.js容器与redis容器链接起来。

redis容器可以通过

获取
docker run -d --name redis -p 6379:6379 dockerfile/redis

而node.js容器基于google/nodejs,其中Dockerfile就是

FROM google/nodejs
WORKDIR   /src
EXPOSE  3000
CMD ["/bin/bash"]

我的 node.js 图像被命名为 nodejs 并由

构建
docker build -t nodejs Dockerfile_path

容器是 运行 通过将我的主机应用程序文件复制到容器中的 src 文件夹并链接现有的 redis 容器

docker run -it --rm -p 8080:3000 --name app -v node_project_path:/src --link redis:redis nodejs

终于成功进入容器,然后npm install安装npm模块,然后node app.js启动应用程序。

但我收到一条错误消息:

Error: Redis connection to localhost:6379 failed - connect ECONNREFUSED

由于 redis 容器暴露给 6379,我的 nodejs 容器正在链接到 redis 容器。在我的 node.js 应用程序中,使用端口 6379 连接到本地主机 redis 服务器应该没问题,为什么实际上它根本不工作

当你link将redis容器转为node容器时,docker已经为你修改hosts文件

然后您应该能够通过以下方式连接到 redis 容器:

var redisClient = require('redis').createClient(6379,'redis'); // 'redis' is alias for the link -> what's in the hosts file.

发件人:https://docs.docker.com/userguide/dockerlinks/

$ sudo docker run -d -P --name web --link db:db training/webapp python app.py

This will link the new web container with the db container you created earlier. The --link flag takes the form:

--link name:alias

Where name is the name of the container we're linking to and alias is an alias for the link name. You'll see how that alias gets used shortly.