如何使用Docker容器内的python套接字连接到服务器?

pes*_*nal 2 python sockets docker

我是Docker的新手,正在尝试在容器中运行python程序。

我的程序需要通过套接字连接到服务器才能正常工作。我已经创建了程序的docker映像及其相应的容器,但是当它到达以下行时会失败,并且我不知道为什么。

 sock.connect((host, port)) 
Run Code Online (Sandbox Code Playgroud)

它显示此错误消息:

[Errno -2]名称或服务未知

它在容器外部运行良好。我可能错过了一些确实很明显的东西,但我看不到。

提前致谢。

Way*_*ner 6

除非您在/etc/hostsDocker容器的文件中进行设置,否则不太可能具有正确的主机名设置。

幸运的是,Docker提供了一种在两个容器之间(环境变量)公开这种信息的好方法。当您链接两个容器时,它们会自动显示。

在一个终端中:

$ 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()
Run Code Online (Sandbox Code Playgroud)

一秒钟:

$ 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()
Run Code Online (Sandbox Code Playgroud)