【问题标题】:Gunicorn Docker container only listens on `0.0.0.0`Gunicorn Docker 容器仅监听 `0.0.0.0`
【发布时间】:2021-06-01 12:43:11
【问题描述】:

我正在尝试为提供我的烧瓶应用程序的 gunicorn 应用程序服务器设置 nginx 反向代理。 gunicorn 容器监听 5000 端口,nginx 监听 80 端口。问题是我仍然可以通过浏览器访问应用程序访问 localhost:5000,即使我已将 gunicorn 设置为仅监听 docker 容器的 localhost,并且所有请求都应该通过 nginx 容器通过端口 80 传递到 gunicorn 容器。这是我的设置。

docker-compose.yml

version: "3.3"
services:
  web_app:
    build:
      context: .
      dockerfile: Dockerfile.web
    restart: always
    ports:
      - "5000:5000"
    volumes:
      - data:/home/microblog
    networks:
      - web

  web_proxy:
    container_name: web_proxy
    image: nginx:alpine
    restart: always
    ports:
      - "80:80"
    volumes:
      - data:/flask:ro
      - ./nginx/config/nginx.conf:/etc/nginx/nginx.conf:ro
    networks:
      - web

networks:
  web:

volumes:
  data:

Dockerfile.web

FROM python:3.6-alpine

# Environment Variables
ENV FLASK_APP=microblog.py
ENV FLASK_ENVIRONMENT=production
ENV FLASK_RUN_PORT=5000
# Don't copy .pyc files to cointainer
ENV PYTHONDONTWRITEBYTECODE=1

# Security / Permissions (1/2)
RUN adduser -D microblog
WORKDIR /home/microblog

# Virtual Environment
COPY requirements.txt requirements.txt
RUN python -m venv venv
RUN venv/bin/pip install -U pip
RUN venv/bin/pip install -r requirements.txt
RUN venv/bin/pip install gunicorn pymysql

# Install App
COPY app app
COPY migrations migrations
COPY microblog.py config.py boot.sh ./
RUN chmod +x boot.sh

# Security / Permissions (2/2)
RUN chown -R microblog:microblog ./
USER microblog

# Start Application
EXPOSE 5000
ENTRYPOINT ["./boot.sh"]

boot.sh

#!/bin/sh
source venv/bin/activate
flask db upgrade
exec gunicorn --bind 127.0.0.1:5000 --access-logfile - --error-logfile - microblog:app

即使我设置了gunicorn --bind 127.0.0.1:5000', in stdout of docker-compose` 我明白了

web_app_1    | [2021-03-02 22:54:14 +0000] [1] [INFO] Starting gunicorn 20.0.4
web_app_1    | [2021-03-02 22:54:14 +0000] [1] [INFO] Listening at: http://0.0.0.0:5000 (1)

我仍然可以在浏览器中从端口 5000 看到该网站。当我明确将其设置为 127.0.0.1 时,我不确定它为什么会在 0.0.0.0 上收听。

【问题讨论】:

    标签: docker nginx flask gunicorn


    【解决方案1】:

    你的 docker-compose 有

    ports:
      - "5000:5000"
    

    它告诉 docker-proxy 监听主机上的 5000 端口并将请求转发到容器。如果您不希望端口 5000 在外部可用,请删除它。

    另外,你没有成功让 gunicorn 只听 127.0.0.1 也很好;如果你这样做了,web_proxy 容器将无法连接到它。所以你不妨撤销你的尝试。

    【讨论】:

    • 谢谢。这完全有道理。我只是不明白如何让 web_app 监听来自 web_proxy 的连接,而不是来自我的浏览器的请求。
    • @TimothyPulliam 容器都存在于其他机器无法访问的专用网络上。在容器中侦听 0.0.0.0 允许接受来自同一专用网络上其他容器的连接,但来自外部世界。
    • @TimothyPulliam(默认情况下;容器可以共享主机网络堆栈,或者做其他事情,但这不是通常的情况)。
    • 我明白这一点。但是,为什么我仍然可以通过指向http://localhost:5000 从我的网络浏览器连接到 web_app 容器?如何将 web_app 服务器限制在 docker 专用网络中?对不起,如果这是一个愚蠢的问题。
    • @TimothyPulliam 通过不使用ports 指令转发端口。
    猜你喜欢
    • 2018-12-04
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    • 2016-05-27
    • 2019-08-08
    • 2015-05-20
    • 2018-12-03
    • 2019-10-10
    相关资源
    最近更新 更多