iAmoric
iAmoric

Reputation: 1965

Python Client Server with Docker - Connection refused

I'm trying to develop a simple client/server application in python.

The client is running in a Docker container whereas the server is running directly on the host machine.

Here is the code of the client:

import socket

def main():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(('127.0.0.1', 8888))
    print (Connected to server)

if __name__ == '__main__':
    main()

and here is the code of the server:

import socket

HOST = '127.0.0.1'
PORT = 8888

print ("Serving on ", PORT)

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    conn, addr = s.accept()
    with conn:
        print('Connected by', addr)

I have the following error:

  File "./main.py", line 5, in main
    s.connect(('127.0.0.1', 8888))
ConnectionRefusedError: [Errno 111] Connection refused

If I run this client outside a container (directly on host machine), i can connect. But I have this error when I run it in a container.

PS: It's not pure Docker container but an IoT Edge module

Do you know what is the problem ? Thanks

Upvotes: 1

Views: 3704

Answers (1)

LinPy
LinPy

Reputation: 18578

first s.connect(('127.0.0.1', 8888)) in the container means to connect to the container itself not the host, to make that works you should run your Container with --network=host

second Option is to supply your host IP address to the client:

s.connect(('HOST_ROUTABLE_IP_ADDRESS', 8888))

Upvotes: 2

Related Questions