美好的一天!我编写了客户端和服务器应用程序,通过docker运行它们,但是客户端应用程序无法连接到服务器。
客户代码:
import requests
import json
class Client:
def attach_comp_to_employee(self, employee_id, company):
try:
res = requests.get('http://0.0.0.0:8080/',
data=json.dumps({"action": "comp_to_employee",
"id": employee_id,
"company": company,
"owner_name": self.user,
"dbname": self.dbname,
"password": self.password}),
timeout=3)
except requests.exceptions.ConnectionError:
res = "Can't connect to server."
except requests.exceptions.Timeout:
res = "Time for connection expired."
finally:
return res
cl = Client("test_user1", "shop", "password1")
print("Send...")
res = cl.attach_comp_to_employee(6, "ABCD")
print(res)
服务器代码:
from aiohttp import web
class Service:
def __init__(self):
self.app = web.Application()
self.app.add_routes([web.get('/', self.handler)])
async def handler(self, request):
return web.json_response({"response": "Hi"})
print("Start...")
ser = Service()
web.run_app(ser.app)
我为它们创建了两个dockerfile。
客户端的Dockerfile:
FROM python:3
WORKDIR /app
ADD . /app
RUN pip3 install requests
CMD ["python3", "client.py"]
用于服务器的Dockerfile:
FROM python:3
WORKDIR /app
ADD . /app
RUN pip3 install aiohttp
CMD ["python3", "server.py"]
然后我创建了docker-compose.yml:
version: '3'
services:
server:
build: ./server
client:
build: ./client
links:
- "server:localhost"
毕竟我的目录如下:
project
|___server
| |__Dockerfile
| |__server.py
|__client
| |__Dockerfile
| |__client.py
|__docker_compose.yml
当我运行docker-compose up
时,我看到以下内容:
如果我用Cntr+ C
打断它,我会看到:
因此服务器正在运行,正在等待请求。
请帮帮我。我的代码有什么问题?我应该怎么做才能连接这两个脚本?
答案 0 :(得分:0)
您的后端容器是服务器-因此它需要侦听特定的端口才能接受客户端请求。
在Dockerfile中公开端口:
FROM python:3
WORKDIR /app
ADD . /app
RUN pip3 install aiohttp
EXPOSE 8080
CMD ["python3", "server.py"]
现在,作为一个旁注,正如@Klaus D.所评论的那样,-docker-compose links
选项应该不再使用。相反,在您的代码中,直接引用服务器容器名称。
祝你好运!