docker - 502 Nginx无法连接到Gunicorn服务器

标签 docker nginx gunicorn

我真是茫然,以至于出了什么问题。

我在单独的Docker容器中运行nginx和gunicorn。 Nginx在端口80上运行,并在8000上转发到gunicorn。我从nginx收到502错误。如果我打到8000端口,那么我的gunicorn服务器会收到200响应。

如果我卸下nginx docker ,然后在笔记本电脑上启动nginx服务器,将流量转发到端口8000,则一切正常。 dockerized nginx服务器设置会出问题吗?

docker-compose.yml

version: '3.3'
services:
  nginx:
    build: ./nginx
    ports:
      - '1337:80'
    depends_on:
      - django-api
  django-api:
    build:
      context: .
      dockerfile: Dockerfile
    command: gunicorn my_app.wsgi:application --log-level verbose --log-file=/var/log/guni --access-logfile=/var/log/gunia --bind 0.0.0.0:8000 --forwarded-allow-ips "*"
    ports:
      - '8000:8000'
    depends_on:
      - mysql
  mysql:
    image: mysql:5
    volumes:
      - type: bind
        source: ./db/docker-entrypoint-initdb.d
        target: /docker-entrypoint-initdb.d
      - type: volume
        source: mysql-data
        target: /var/lib/mysql
    environment:
        MYSQL_ROOT_PASSWORD: toor
    networks:
      - backend
    ports:
      - '3306:3306'
volumes:
  mysql-data:
  static_volume:
networks:
  backend:

Gunicorn Dockerfile
FROM python:3
ENV PYTHONUNBUFFERED 1
ENV DJANGO_SETTINGS_MODULE dori.settings.dev
WORKDIR /app
COPY . /app
RUN pip install --upgrade pip
RUN pip install --no-cache-dir -r requirements.txt

# Port to expose
EXPOSE 8000

nginx.conf
upstream hello_django {
    server localhost:8000;
}

server {
    listen 80;
    location / {
        proxy_pass http://hello_django;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
    }
}

最佳答案

问题出在您的nginx配置文件中。您正在尝试将来自nginx容器的请求转发到端口8000上的容器本身,只需将您的nginx配置文件更改为此:

upstream hello_django {
    server django-api:8000;
}

server {
    listen 80;
    location / {
        proxy_pass http://hello_django;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
    }
}

django-api 是docker-compose创建的网络中您的容器的服务名称,当您尝试连接到它时,其他服务可以在本地网络中解析它。

关于docker - 502 Nginx无法连接到Gunicorn服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59745091/

相关文章:

python - Flask-Bokeh-Gunicorn : Models must be owned by a single document

python - manage.py 是组织/编写 Flask 应用程序的正确方法吗?

windows - 在Windows Hyper-V容器中运行不受信任的代码

javascript - Redis连接失败

nginx - Pagespeed Javascript 缩小/连接 - 添加横幅和页脚

nginx - Nginx 上 Drupal 的 AMP 参数错误

python - 如何使用 Gunicorn 和 Varnish 运行 Flask?

docker - 卡夫卡 Spark 流: Broker may not be available [Docker]

node.js - docker swarm 中容器之间的通信

nginx - Kubernetes 仪表板 : Dashboard keeps cancelling connection to pod, 导致用户网关错误