Nginx无法路由请求至uWSGI部署的Flask服务问题解决
Nginx搭配uWSGI部署Flask项目路由失败问题解决
Nginx配置文件(nginx.conf)
server { listen 80; server_name <你的机器IP/域名>;(本地环境填localhost,我在WSL中用了实际IP) location / { include uwsgi_params; uwsgi_pass web_app:5000;(网上推荐的.sock文件、http://或unix:前缀都无效,直接用Docker Compose里的服务名即可) } }
Docker Compose配置文件
version: '3.7' services: web_app: build: . container_name: kpi-dashboard ports: - 5000:5000 depends_on: - db nginx: build: ./nginx container_name: nginx restart: always ports: - "80:80" depends_on: - web_app db: image: postgres:13-alpine container_name: postgresql volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_DB=postgres ports: - 5432:5432 volumes: postgres_data:
Nginx Dockerfile
FROM nginx RUN rm /etc/nginx/conf.d/default.conf (必须删除默认配置,否则自定义配置不会生效) COPY nginx.conf /etc/nginx/conf.d/ (网上有其他复制路径的方案,但只有这个路径有效) EXPOSE 80
Web应用Dockerfile
FROM python:3.8.16-slim-buster RUN apt-get update RUN apt-get install gcc -y && apt-get install python3-dev -y && apt-get install libpq-dev -y ENV PYTHONPATH=${PYTHONPATH}:${PWD} RUN pip install poetry WORKDIR /app COPY pyproject.toml /app/ COPY . /app/ RUN poetry config virtualenvs.create false RUN poetry install --no-dev EXPOSE 5000 CMD ["uwsgi", "--ini", "wsgi.ini"]
uWSGI配置文件(wsgi.ini)
[uwsgi] module = app (项目入口文件为app.py时用这个,若入口是wsgi.py则改为wsgi:app) socket = 0.0.0.0:5000 callable = app (uWSGI默认把应用实例识别为application,需配置此项或在主文件中调整实例名) processes = 1 threads = 1 master = true vacuum = true die-on-term = true
问题解决步骤
- 解决404问题:修改Nginx Dockerfile中nginx.conf的复制路径为
COPY nginx.conf /etc/nginx/nginx.config - 解决路由问题:更新上述相关配置文件内容(即调整为上述正确配置)
内容的提问来源于stack exchange,提问作者Prakash
相关产品推荐
相关产品推荐

