[英]How to set-up NodeJs client and server using docker-compose?
I have the following node.js
scripts:我有以下
node.js
脚本:
client.js客户端.js
const net = require('net');
const client = new net.Socket();
client.connect(9233, 'server', (error) => {
console.log('Connected to packet feed');
});
client.on('error', (err) => {
console.log(err);
})
server.js服务器.js
const net = require('net');
const server = net.createServer((socket) => {
});
server.listen(9233, 'localhost');
And the following docker-compose.yaml
以及以下
docker-compose.yaml
version: '3'
services:
server:
build: .
volumes:
- ./:/usr/src/app
command: node server.js
ports:
- "9233:9233"
client:
build: .
volumes:
- ./:/usr/src/app
environment:
command: node clients.js
links:
- server
depends_on:
- server
If I run node server.js
and node client.js
on my machine, they connect to each other sucessfully.如果我在我的机器上运行
node server.js
和node client.js
,它们会成功地相互连接。
But if I run docker-compose up
, I'll get the following error:但是如果我运行
docker-compose up
,我会得到以下错误:
client_1 | Error: connect ECONNREFUSED 172.26.0.2:9233
client_1 | at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1056:14) {
client_1 | errno: 'ECONNREFUSED',
client_1 | code: 'ECONNREFUSED',
client_1 | syscall: 'connect',
client_1 | address: '172.26.0.2',
client_1 | port: 9233
client_1 | }
What am I doing wrong?我究竟做错了什么? I've tried everything I could, including
docker-compose run --service-ports
instead of docker-compose up
.我已经尝试了我能做的一切,包括
docker-compose run --service-ports
而不是docker-compose run --service-ports
docker-compose up
。
In the server.listen()
call, you need to specify the magic IPv4 "everywhere" address 0.0.0.0.在
server.listen()
调用中,您需要指定神奇的 IPv4“无处不在”地址 0.0.0.0。 If you specify localhost
there, it will be unreachable from outside the container.如果您在那里指定
localhost
,它将无法从容器外部访问。 (It will only accept connections coming from the container's localhost
, and each container has its own localhost
.) (它只接受来自容器的
localhost
连接,并且每个容器都有自己的localhost
。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.