Skip to main content
 首页 » 编程设计

python之在 docker 中通过 nginx 和 gunicorn 服务 flask

2024年10月17日2898°冷暖

玩 flask 我想在 docker 中进行真正的设置和运行。这意味着 flask 应该通过 nginx 和 gunicorn 提供服务。我建立了一个示例代码存储库 https://github.com/geoHeil/pythonServing但到目前为止还不能让 nginx 正常工作。

Flask 在 application:5000 上提供服务,docker 应该将应用程序解析为其各自的名称。

Nginx配置如下:

server { 
 
    listen 8080; 
    server_name application; 
    charset utf-8; 
 
    location / { 
        proxy_pass http://application:5000; 
        proxy_set_header Host $host; 
        proxy_set_header X-Real-IP $remote_addr; 
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
    } 
} 

我觉得不错。到目前为止我找不到问题。

编辑

撰写文件在这里。开始的命令是

docker-compose build 
docker-compose up 
 
version: '2' 
services: 
  application: 
    restart: always 
    build: ./application 
    command: gunicorn -w 4 --bind :5000 wsgi:application 
    links: 
      - db 
    expose: 
     - "5000" 
    ports: 
      - "5000:5000" 
  nginx: 
    restart: always 
    build: ./nginx 
    links: 
      - application 
    expose: 
      - 8080 
    ports: 
      - "8880:8080" 

请您参考如下方法:

您的 nginx 配置文件位于错误的位置。

修复步骤:

sudo docker-compose down 

删除nginx镜像:

sudo docker images 
sudo docker rmi  
REPOSITORY                       TAG                 IMAGE ID            CREATED              SIZE 
pythonserving_nginx              latest              152698f13c7a        About a minute ago   54.3 MB 
 
sudo docker rmi pythonserving_nginx 

现在更改 nginx Dockerfile:

FROM nginx:1.11.8-alpine 
MAINTAINER geoheil 
 
ADD sites-enabled.conf /etc/nginx/conf.d/sites-enabled.conf 

请注意nginx配置的位置。

现在试试这个 docker-compose 文件(使用用户定义的网络):

version: '2' 
services: 
  application: 
    restart: always 
    build: ./application 
    command: gunicorn -w 4 --bind :5000 wsgi:application 
    networks: 
      - testnetwork 
    expose: 
     - "5000" 
    ports: 
      - "5000:5000" 
  db: 
    restart: always 
    image: postgres:9.6.1-alpine 
    networks: 
      - testnetwork 
    ports: 
      - "5432:5432" 
    environment: 
      - POSTGRES_USER=d 
      - POSTGRES_PASSWORD=d 
      - POSTGRES_DB=d 
    volumes: 
      - ./postgres:/var/lib/postgresql 
  nginx: 
    restart: always 
    build: ./nginx 
    networks: 
      - testnetwork 
    expose: 
      - 8080 
    ports: 
      - "8880:8080" 
networks: 
  testnetwork: 

并调出容器:

sudo docker-compose up 

浏览到 http://localhost:8880