rj487
rj487

Reputation: 4634

Rails send request to other container [Failed to open TCP connection]

I am trying to do multiple node distribution systems by multiple Rails node + docker + MySQL + Redis.

Therefore, my main node needs to communicate with other nodes.

Here is my docker-compose.yml

**version: '2'
services:
  db:
    image: mysql:5.7
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=password
      - MYSQL_DATABASE=pubsub_1_development
      - MYSQL_USER=appuser
      - MYSQL_PASSWORD=password
    ports:
      - "3308:3306"

  redis:
    image: 'redis:4.0-alpine'

  app:
    image: pubsub_2:1.0.8
    command: /bin/sh -c "rm -f ./tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    volumes:
      - ".:/pubsub_2"
    ports:
      - "3001:3000"
    depends_on:
      - db
      - redis
      - sub_node
      - pub_node
    links:
      - db
      - redis
      - sub_node
      - pub_node
    environment:
      DB_USER: root
      DB_NAME: pubsub_1_development
      DB_PASSWORD: password
      DB_HOST: db
      REDIS_CABLE_PORT: redis://redis:6379/1
      SUB_NODE: 0.0.0.0:4001
      PUB_NODE: 0.0.0.0:4000
    stdin_open: true
    tty: true

  sub_node:
    image: sub_node:1.0.1
    command: /bin/sh -c "rm -f /sub_node/tmp/pids/server.pid && bundle exec rails s -p 4001 -b '0.0.0.0'"
    ports:
      - "4001:4001"
    environment:
      DB_USER: root
      DB_NAME: pubsub_1_development
      DB_PASSWORD: password
      DB_HOST: db
      REDIS_CABLE_PORT: redis://redis:6379/1
    tty: true
    expose:
      - "4001"


  pub_node:
    image: pub_node:1.0.1
    command: /bin/sh -c "rm -f /pub_node/tmp/pids/server.pid && bundle exec rails s -p 4000 -b '0.0.0.0'"
    ports:
      - "4000:4000"
    environment:
      DB_USER: root
      DB_NAME: pubsub_1_development
      DB_PASSWORD: password
      DB_HOST: db
      REDIS_CABLE_PORT: redis://redis:6379/1
    tty: true
    expose:
      - "4000"**

However, when I try to use app node to send the request to pub_node, it threw this error.

Errno::ECONNREFUSED: Failed to open TCP connection to 127.0.0.1:4000 (Connection refused - connect(2) for "127.0.0.1" port 4000)
from /usr/local/lib/ruby/2.5.0/net/http.rb:939:in `rescue in block in connect'

I was doing post by this code.

rvlist = '127.0.0.1:4000'
HTTParty.post("http://#{rvlist}/publish", options)

It works in my development mode without the docker environment.

Upvotes: 1

Views: 1223

Answers (1)

Zoran Majstorovic
Zoran Majstorovic

Reputation: 1609

Networking in docker-compose:

Each container for a service joins the default network and is both reachable by other containers on that network, and discoverable by them at a hostname identical to the container name.

Reference: https://docs.docker.com/compose/networking/

In your case, any container within docker-compose can open the TCP connection to pub_node container using its container name and port pub_node:4000

Upvotes: 1

Related Questions