Adam
Adam

Reputation: 5253

How to set-up NodeJs client and server using docker-compose?

I have the following node.js scripts:

client.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

const net = require('net');

const server = net.createServer((socket) => {
});

server.listen(9233, 'localhost');

And the following 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.

But if I run docker-compose up, I'll get the following error:

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.

Upvotes: 1

Views: 590

Answers (1)

David Maze
David Maze

Reputation: 159998

In the server.listen() call, you need to specify the magic IPv4 "everywhere" address 0.0.0.0. If you specify localhost there, it will be unreachable from outside the container. (It will only accept connections coming from the container's localhost, and each container has its own localhost.)

Upvotes: 2

Related Questions