我正在尝试将容器A中的TCP客户端连接到容器B中的TCP服务器。运行docker-compose up会导致客户端出现ECONNREFUSED错误。为什么呢?
TCP-client看起来像这样:
var net = require('net');
var client = new net.Socket();
client.connect(1337, function() {
console.log('Connected');
client.write('Hello, server! Love, Client.');
});
client.on('data', function(data) {
console.log('Received: ' + data);
// client.destroy(); // kill client after server's response
});
client.on('close', function() {
console.log('Connection closed');
});
TCP客户端Dockerfile如下所示:
FROM node:latest
RUN mkdir /app
WORKDIR /app
ADD . /app
ADD package.json /app
RUN npm install
EXPOSE 1337
ENV PATH /app/node_modules/.bin:$PATH
CMD npm start
TCP服务器如下所示:
var net = require('net');
var server = net.createServer(function(socket) {
socket.write('Echo server\r\n');
socket.pipe(socket);
});
server.listen(1337);
TCP服务器Dockerfile如下所示:
FROM node:latest
RUN mkdir /app
WORKDIR /app
ADD . /app
ADD package.json /app
RUN npm install
EXPOSE 1337
ENV PATH /app/node_modules/.bin:$PATH
CMD npm start
docker-compose.yml看起来像这样:
version: "3"
services:
tcpclient:
build: ./tcpclient
ports:
- "8000:8000"
depends_on:
- tcpserver
tcpserver:
build: ./tcpserver
ports:
- "8001:1337"
连接错误如下所示:
tcpclient_1 | > http-service@1.0.0 start /app
tcpclient_1 | > node tcpclient.js
tcpclient_1 |
tcpclient_1 | events.js:137
tcpclient_1 | throw er; // Unhandled 'error' event
tcpclient_1 | ^
tcpclient_1 |
tcpclient_1 | Error: connect ECONNREFUSED 127.0.0.1:1337
tcpclient_1 | at Object._errnoException (util.js:1003:13)
tcpclient_1 | at _exceptionWithHostPort (util.js:1024:20)
tcpclient_1 | at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1194:14)
tcpclient_1 | npm ERR! code ELIFECYCLE
非常感谢帮助
答案 0 :(得分:1)
这里有多个问题。 我不确定容器中的 localhost 是否与您的主机位于同一个界面中。此外,港口界限是8001.但是,我会重新采用另一种方法:
使用link
,您可以使用其名称引用其他容器主机。
我会尝试:
1)添加tcpclient
容器定义:
links:
- tcpserver
2)在tcp服务器中保留1337:1337(为什么客户端暴露TCP端口btw?)
3)使用client.connect(1337, 'tcpserver', function(...){...}