繁体   English   中英

无法使用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)

我为他们创建了两个dockerfiles。

客户端的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打断它,我会看到:

打断

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

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

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

公开Dockerfile中的端口:

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

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

祝好运!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM