Connection refused between containers when using Docker compose

Viewed 2199

I have been testing Docker for learning purposes in a GCP VM and I have two containers in my project:

  1. First container is a nodejs API which returns json formatted data when accessing VM address on port 80.
  2. Second container is a python flask server which displays this data on a website when accessing VM address on port 5000.

I have tested both containers and I am able to access them when I do it from public network. What I do in the python flask server is accessing API using VM IP public address with this simple code and display the content in the browser:

from flask import Flask
from urllib.request import urlopen
import json
app = Flask(__name__)
@app.route("/")
def dataserver():
        with urlopen("http://xxx.xxx.xxx.xxx/api/devices") as url:
                data = json.loads(url.read().decode())
                return data
if __name__ == "__main__":
        app.run(host="0.0.0.0", port=int("5000"), debug=True)

This gives no trouble and content is displayed as expected. But now I want to run this containers using docker-compose and make them able to communicate within local network using docker-compose service name instead of public IP address. I have replaced this line of code but connection is refused:

with urlopen("http://nodejs-service/api/devices") as url:

This is my docker-compose file:

version: '3'

services:
  nodejs-service:
    build: ./nodejsAppDocker
    volumes:
      - ./nodejsAppDocker
    ports:
      - 80:8080
    networks:
      - local

  python-service:
    build: ./pythonAppDocker
    volumes:
      - ./pythonAppDocker
    ports:
      - 5000:5000
    depends_on:
      - nodejs-service
    networks:
      - local

networks:
  local:
    driver: bridge

I created a local network as you can see in docker-compose.yml file but python container is not able to communicate with nodejs container using service name. This is the message I get on website:

urllib.error.URLError: <urlopen error [Errno 111] Connection refused>

Is there something I am missing?

1 Answers

As Alex said, specifying port in the URL makes it work. For some reason I though the connection had to be done over container external ports which makes no sense and is obviously wrong. David is also right when he says networks are not necessary. I deleted network declarations from compose file and it also works.

Related