Ngnix和docker compose - 不返回静态文件

时间:2018-04-18 15:40:38

标签: docker nginx docker-compose gunicorn

这是my docker-file.yml

version: '2'
services:

  nginx:
    image: nginx:latest
    ports:
      - '80:80'
      - '443:443'
    volumes:
      - ./conf.d:/etc/nginx/conf.d/
      - ./logs/nginx_access.log:/var/log/nginx_access.log
      - ./logs/nginx_error.log:/var/log/nginx_error.log
      - ./src/app/static:/flask-app/src/app/static
    depends_on:
      - web

  web:
    build: ./
    command: gunicorn manage:app --bind 0.0.0.0:8000 --access-logfile=logs/gunicorn_access_log.txt
    ports:
    - '8000:8000'
    volumes:
    - ./:/flask-app
    environment:
      DATABASE_URL: postgresql://postgres:pass@localhost/flask_deploy
      REDIS_HOST: redis
      SECRET_KEY: 'BbGd3qe$dsf1'
      CONFIG_NAME: 'prod'
    links:
      - postgres:postgres
      - redis:redis
    depends_on:
      - postgres
      - redis

  postgres:
    image: postgres:9.4
    volumes:
      - ./psql-data:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: 'pass'
      POSTGRES_DB: 'flask_deploy'
    ports:
      - '5432:5432'

  redis:
    image: "redis:3.0-alpine"
    command: redis-server
    ports:
      - '6379:6379'

这是我的ngnix配置(web是来自docker-compose文件的名称):

server {
    listen 80;
    server_name web;

    # запись доступа и журналы ошибок в /var/log
    access_log /var/log/nginx_access.log;
    error_log /var/log/nginx_error.log;

    location / {
        # переадресация запросов приложений на сервер gunicorn
        proxy_pass http://web:8000;
    }

    location /static {
        # обрабатывать статические файлы напрямую, без пересылки в приложение
        autoindex on;
        alias /flask-app/src/app/static;
        expires 1d;
    }
}

我的网站在127.0.0.1(无端口)上可用。但是..我的静态文件有问题。 Flask url_for生成网址:

http://web:8000/static/img/do.jpg

此链接不可用。

我可以试试这个:

http://127.0.0.1:8000/static/img/do.jpg

我看到了照片。但这张照片是由gunicorn而不是ngnix返回的:(

我是docker-compose和ngnix的初学者。也许,关于我的配置的一些评论?谢谢!

1 个答案:

答案 0 :(得分:0)

解决方案:

proxy_set_header Host $host:8000;

完整配置:

server {
    listen 80;
    server_name localhost;

    root /flask-app/src/app;

    access_log /var/log/nginx_access.log;
    error_log /var/log/nginx_error.log;

    location / {
        proxy_set_header Host $host:8000;
        proxy_pass http://web:8000;
    }

    location /static {
        autoindex on;
        expires 1d;
    }
}