不能 运行 客户端-服务器应用程序 docker

Can't run client-server application with docker

美好的一天!我编写了客户端和服务器应用程序,我通过 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)

我为他们创建了两个 docker文件。

客户端的 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 我看到这个:

docker-compose up

如果我用 Cntr+ C 打断它,我会看到这个:

interrupt

所以服务器 运行正在等待请求。

请帮帮我。我的代码有什么问题?我应该怎么做才能连接这两个脚本?

您的后端容器是服务器 - 因此它需要监听特定的 端口 以接受客户端请求。

在您的 Dockerfile 中公开端口:

FROM python:3
WORKDIR /app
ADD . /app
RUN pip3 install aiohttp
EXPOSE 8080
CMD ["python3", "server.py"]

现在,作为旁注,正如@Klaus D. 评论的那样,-docker-compose links 选项不应再被使用。相反,在您的代码中,直接引用服务器容器名称。

祝你好运!