Reputation: 103
I have an ubuntu docker image that has python(2.7) installed in it. I am trying to create a python socket server inside the image. I am passing my host machine's IP as environmental variable while starting the container. This is how I start my container:
docker run -it -e host_ip=`hostname -I | awk '{ print $1 }'` ubuntu
After entering my container, I run this python script:
import socket
import os
host_ip = os.environ['host_ip']
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host_ip, 9876))
s.listen(10)
while 1:
conn, addr = s.accept()
data = conn.recv(1024)
print data
conn.send(str.encode('hello world\nbye world'))
conn.close()
if data == "EOF":
break
s.close()
When running the script, this is the error I get:
Traceback (most recent call last): File "SocketServer.py", line 5, in s.bind((host_ip, 9876)) File "/usr/lib/python2.7/socket.py", line 228, in meth return getattr(self._sock,name)(*args) socket.error: [Errno 99] Cannot assign requested address
What mistake am I doing?
Upvotes: 0
Views: 2276
Reputation: 48345
The container is isolated from the host network stack by default. Addresses assigned to host network interfaces are not available to the container. This is part of what makes it a container.
You should either bind to the container's address and arrange to forward ports from the host to the container or you should make the container share the host network.
For example, tell the application to bind to 127.0.0.1 and then forward the port:
docker run -it -e host_ip=127.0.0.1 -p 9876:9876 ...
Or make the container use the host network:
docker run -it -e host_ip=127.0.0.1 --network=host ...
Upvotes: 4