反向代理Nginx+Docker+Django项目后,在此服务器上找不到请求的资源

问题描述 投票:0回答:2

当我尝试访问 localhost/auth/ 时遇到问题,这可能是由于 nginx 配置或可能是另一个其他问题。以下是我尝试向代理地址 localhost/auth/

发出请求后从 nginx 日志中获得的结果
reverse-proxy      | 0.0.0.0 - - [28/Aug/2020:08:21:47 +0000] "GET /api/ HTTP/1.1" 404 159 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) 

当我访问 http://localhost/admin/ 时,管理员登录页面将按预期呈现,如下所示。另外,在 http://localhost/doc/ redocs 文档 页面也会呈现。

项目结构

├── nccggbot
│     ├── chatbot/
│     └── core/
│     │     ├── __init__.py
│     │     ├── asgi.py
│     │     ├── settings.py
│     │     ├── urls.py
│     │     ├── wsgi.py
│     ├── static/
│     │     ├── admin/
│     │     ├── django_extensions/
│     │     |── drf-yasg
│     │     ├── rest_framework
│     │ 
│     ├── Dockerfile
│     ├── manage.py
│     ├── requirements.txt
│ 
│    
├──reverse_proxy/
│   ├── default.conf
│   └── Dockerfile
├──docker-compose-deploy.yml
├──README.md

core/urls.py

from django.contrib import admin
from django.urls import include,path

from drf_yasg.views import get_schema_view
from drf_yasg import openapi
from rest_framework import permissions
from django.conf import settings
from django.conf.urls.static import static 


schema_view = get_schema_view(
   openapi.Info(
      title="NCCG ChatBot API",
      default_version='v1.0.0',
      description="The nccg chatbot rest API",
   ),
   public=True,
   permission_classes=(permissions.AllowAny,),
)


urlpatterns = [
    path('admin/', admin.site.urls),
    path('doc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
    path('api-auth/', include('rest_framework.urls')),
    path('api/', include('chatbot.urls'))
]

设置.py

"""
Django settings for core project.

Generated by 'django-admin startproject' using Django 3.1.

For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""

from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve(strict=True).parent.parent


DEBUG = bool(int(os.environ.get("DEBUG", default=0)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY =  os.environ.get("SECRET_KEY")


ALLOWED_HOSTS = ['*']

# ALLOWED_HOSTS_ENV = os.environ.get('ALLOWED_HOSTS')

# if ALLOWED_HOSTS_ENV:
#     ALLOWED_HOSTS.extend(ALLOWED_HOSTS_ENV.split(','))


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'chatterbot.ext.django_chatterbot',
    'rest_framework',
    'drf_yasg',
    'chatbot'
]

# ChatterBot settings

CHATTERBOT = {
    'name': 'NCCG Support Bot',
    'django_app_name': 'django_chatterbot'
}


MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'core.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'core.wsgi.application'


REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ]
}


# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

print(DEBUG)

DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME':  'db.sqlite3',
        }
    }


# if DEBUG is False:
#     DATABASES = {
#         'default': {
#             'ENGINE': 'django.db.backends.sqlite3',
#             'NAME': BASE_DIR / 'db.sqlite3',
#         }
#     }

# else:
#     DATABASES = {
#     "default": {
#         "ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.sqlite3"),
#         "NAME": os.environ.get("SQL_DATABASE", os.path.join(BASE_DIR, "db.sqlite3")),
#         "USER": os.environ.get("SQL_USER", "user"),
#         "PASSWORD": os.environ.get("SQL_PASSWORD", "password"),
#         "HOST": os.environ.get("SQL_HOST", "localhost"),
#         "PORT": os.environ.get("SQL_PORT", "5432"),
#     }
#     }


# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_URL = '/static/static/'
MEDIA_URL = '/static/media/'

STATIC_ROOT = '/vol/web/static'
MEDIA_ROOT = '/vol/web/media'

# STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),]

NGINX 配置文件

upstream webserver {
    server nccgbot-service:8000;
}


server {
    listen 80;
    gzip on;

    location /auth {
        proxy_pass http://webserver/api-auth;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
        client_max_body_size 100M;
    }

    location /doc {
        proxy_pass http://webserver/doc;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
        client_max_body_size 100M;
    }

    location / {
        proxy_pass http://webserver;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
        client_max_body_size 100M;
    }


    location /static {
        autoindex on;
        alias /vol/static;
    }

}

Docker 撰写文件

version: '3.7'

services: 
  # Chat bot 
  nccgbot-service:
    container_name: nccgbot-service
    image: nccgbot-service
    build:
      context: ./nccgbot_service

    command: sh -c "python manage.py makemigrations && python manage.py collectstatic --no-input  && python manage.py migrate && gunicorn core.wsgi:application --workers 2 --bind 0.0.0.0:8000"

    volumes:
      - static_data:/vol/web

    env_file:
      - ./.env

    expose: 
      - "8000"

    restart: on-failure
  
  # proxies requests to internal services
  reverse_proxy:
    build:
      context: ./reverse_proxy
    restart: always
    image: reverse-proxy
    container_name: reverse-proxy
    volumes:
      - static_data:/vol/static

    ports:
      - "80:80"

    depends_on:
      - nccgbot-service

volumes:
  static_data:

chatbot/urls.py

from django.conf.urls import url
from chatbot.views import ChatterBotApiView


urlpatterns = [
    url(r'^chatbot/', ChatterBotApiView.as_view(), name='chatbot'),
]

**访问时的浏览器输出

localhost/api-auth
**

django docker nginx django-rest-framework nginx-reverse-proxy
2个回答
0
投票

rest_framework.urls 没有索引视图:

urlpatterns = [
    url(r'^login/$', views.LoginView.as_view(template_name='rest_framework/login.html'), name='login'),
    url(r'^logout/$', views.LogoutView.as_view(), name='logout'),
]

所以

/auth/login
应该有效。而且,它不会做你想象的那样。这提供了 Django 的标准登录和注销视图,并且不通过 REST 进行身份验证。请查看第三方软件包。 并查看 Django Vue Auth Demo,讨论使用分离前端通过 REST 进行身份验证时的一些常见错误和陷阱。


0
投票

我也有类似的问题。原因是 Settings.py 中的 Debug = False 并且安装是全新的生产环境。 我的解决方案是设置 Debug = True 直到定义视图之后。

https://stackoverflow.com/questions/14951468/who-generates-the-default-page-of-django-welcome-page#:~:text=如果%20your%20urls.py%20是%20page %20you're%20seeing.&text=%20default%20landing%20page%20that,html%22.

如果你的 urls.py 为空(如不包含任何匹配 url 的模式)并且 Django 处于调试模式(设置中的 DEBUG = True),那么 Django 会触发你所看到的页面。第一次运行 django Web 应用程序时看到的默认登录页面是“default_urlconf.html”。

© www.soinside.com 2019 - 2024. All rights reserved.