Skip to main content
 首页 » 编程设计

python之在 Docker 中运行的 Aiohttp 和 NGINX

2024年12月31日28linjiqin

长话短说

我想在 nginx 网络服务器上运行 aiohttp 后端服务。两者都应该在 docker 容器中运行。此外,我的前端角度应用程序应该访问我的后端服务。

预期行为

我希望 nginx 网络服务器可以连接到我在 docker 中运行的后端系统 aiohttp。

实际行为

当我尝试在我的 aiohttp 后端服务上调用 GET 请求时,docker 日志中总是出现错误。

nginx_1 | 2018/09/29 13:48:03 [error] 6#6: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.19.0.1, server: , request: "GET /toolservice/volatility?command=pslist HTTP/1.1", upstream: "http://172.19.0.2:80/toolservice/volatility?command=pslist", host: "localhost" nginx_1 | 172.19.0.1 - - [29/Sep/2018:13:48:03 +0000] "GET /toolservice/volatility?command=pslist HTTP/1.1" 502 576 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36" "-"

Docker-compose.yml

version: '3' 
 
services: 
 
    nginx: 
      build: ./nginx 
      restart: always 
      depends_on: 
        - toolservice 
        - ifs 
      ports: 
       - "80:80" 
 
    ifs: 
      restart: always 
      build: ../ifsbackend 
      ports: 
        - "8002:8000" 
 
    toolservice: 
      restart: always 
      build: ../ToolService 
      ports: 
        - "8001:8000" 

Dockerfile nginx 网络服务器

FROM nginx:1.13-alpine 
 
RUN rm /etc/nginx/conf.d/default.conf 
COPY conf/server.conf /etc/nginx/conf.d/ 

Dockerfile aiohttp 后端

FROM python:3.6.6-alpine 
COPY tool / 
COPY requirements.txt / 
COPY toolservice_config.yaml / 
RUN apk update && apk add \ 
    python3-dev \ 
    musl-dev \ 
    gcc \ 
    && pip install -r requirements.txt \ 
    && pip install virtualenv 
RUN python3 -m virtualenv --python=python3 virtualenv 
EXPOSE 8080 
CMD [ "python", "server.py" ] 

Nginx 网络服务器配置

#upstream toolservice { 
 # server 0.0.0.0:8001 fail_timeout=0; 
#} 
 
server { 
    listen 80; 
 
    #server_name localhost; 
    proxy_buffers 8 16k; 
    proxy_buffer_size 32k; 
 
    location /toolservice { 
        proxy_pass http://toolservice; 
        proxy_redirect default; 
 
        proxy_set_header Host $host; 
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
 
 
    } 
    location /ifs { 
      proxy_pass http://ifs; 
      proxy_redirect default; 
 
      proxy_set_header Host $host; 
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
 
    } 
} 

Aiohttp 工具服务后端

from aiohttp import web 
from routes import setup_routes 
from settings import config 
 
app = web.Application() 
setup_routes(app) 
app['config'] = config 
web.run_app(app, port=8001) 

请您参考如下方法:

Aiohttp 在容器 toolservice 的 8001 端口上运行,但是你代理到 80 端口。

proxy_pass http://toolservice; 

尝试代理到 8001:

proxy_pass http://toolservice:8001; 

也许您需要修复 toolservice 容器的端口发布 - 我不是 100% 确定:

  ports: 
    - "8001:8001"