pespinal
pespinal

Reputation: 23

How can I connect to a server using python sockets inside a Docker container?

I am new to Docker and I am trying to run my python program in a container.

My program needs to connect to a server through a socket in order to work fine. I have created my program's docker image and its respective container, but when it gets to the following line it fails, and I have no idea why.

 sock.connect((host, port)) 

It shows this error message:

[Errno -2] Name or service not known

It runs just fine outside the containter. I'm probably missing something really obvious but I can't see it.

Thanks in advance.

Upvotes: 2

Views: 6138

Answers (1)

Wayne Werner
Wayne Werner

Reputation: 51787

Unless you've set it up in your /etc/hosts file of your docker container, it's unlikely that you're going to have the proper hostname setup.

Luckily for you, Docker provides a nice way to expose this sort of information between two containers - environment variables. They're automatically exposed when you link two containers.

In one terminal:

$ docker run --name camelot -it -p 5000 --rm python
Python 3.5.2 (default, Jul  8 2016, 19:17:03) 
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import socketserver
>>> 
>>> class MyHandler(socketserver.BaseRequestHandler):
...     def handle(self):
...         self.data = self.request.recv(2048).strip()
...         print('{} wrote: '.format(self.client_address[0]))
...         print(self.data)
...         self.request.sendall(self.data.upper())
... 
>>> 
>>> server = socketserver.TCPServer(('0.0.0.0', 5000), MyHandler)
>>> server.serve_forever()

In a second:

$ docker run --rm -it --link camelot python
Python 3.5.2 (default, Jul  8 2016, 19:17:03) 
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> import socket
>>> 
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> s.connect((os.environ['CAMELOT_PORT_5000_TCP_ADDR'],
...            int(os.environ['CAMELOT_PORT_5000_TCP_PORT'])))
>>> s.send(b'Hey dude!')
9
>>> print(s.recv(2048))
b'HEY DUDE!'
>>> s.close()

Upvotes: 10

Related Questions