Gunicorn Docker 容器仅侦听“0.0.0.0”

Tim*_*iam 1 nginx flask gunicorn docker

我正在尝试设置一个 nginx 反向代理到为我的 Flask 应用程序提供服务的 Gunicorn 应用程序服务器。Gunicorn 容器监听端口 5000,nginx 监听端口 80。问题是我仍然可以通过浏览器访问该应用程序localhost:5000,即使我已将 Gunicorn 设置为仅监听 docker 容器的 localhost 以及所有请求应该通过端口 80 通过 nginx 容器到达 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:
Run Code Online (Sandbox Code Playgroud)

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"]
Run Code Online (Sandbox Code Playgroud)

启动文件

#!/bin/sh
source venv/bin/activate
flask db upgrade
exec gunicorn --bind 127.0.0.1:5000 --access-logfile - --error-logfile - microblog:app
Run Code Online (Sandbox Code Playgroud)

即使我已经设置了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)
Run Code Online (Sandbox Code Playgroud)

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

hob*_*bbs 5

你的 docker-compose 有

ports:
  - "5000:5000"
Run Code Online (Sandbox Code Playgroud)

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

另外,还好你没有成功让gunicorn只听127.0.0.1;如果这样做,web_proxy容器将无法连接到它。因此,您不妨撤消这样做的尝试。