I have a server and a client docker container run on the same AWS EC2, I try to let them communicate with each other by using Tcp protocol but got:
Traceback (most recent call last):
File "testClient.py", line 13, in <module>
s.connect((HOST, PORT))
ConnectionRefusedError: [Errno 111] Connection refused
Here is my code for server container:
import socket
import sys
HOST, PORT = "localhost", int(sys.argv[2])
protocol = sys.argv[1]
print(protocol, HOST, PORT)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (HOST, PORT)
sock.bind(server_address)
sock.listen(1)
connection, client_address = sock.accept()
while True:
data = connection.recv(20)
if not data: break
print('received data: ', data)
connection.send(data.upper())
connection.close()
And client container:
import socket
import sys
protocol = sys.argv[1]
HOST = sys.argv[2]
PORT = int(sys.argv[3])
print(protocol, HOST, PORT)
# HOST, PORT = "localhost", 9998
command = " ".join(sys.argv[4:])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send(command.encode('utf-8'))
data = s.recv(1024)
s.close()
print('received data: ', data)
To avoid potential bugs, I just run docker with interactive shell and then run python code manually:
docker run -it --rm --name node_server -p 4444:4444 server
/# python3 Server.py ts 4444
docker run --rm -it --name node_client -p 8888:8888 client
/# python3 Client.py ts 172.17.0.2 4444 put a 3
The ip address I put in client side is from docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' server
I don't get any luck on exposure server's port, so I also tried to add --link server
to run client container and ---network=test
to both containers but it gives me the same error.
Btw, I use telnet 172.17.0.2 4444
on the host machine and it also gives me connection refused.
My other classmates who use java to do the same thing on the same environment don't get any connection problem.
I'm new to the docker, but from my point of view, I think the problem comes from Docker configuration instead of my code. Any suggestion will be appreciated.