如何解决错误反向代理Nginx + Docker + Django项目后在此服务器上找不到请求的资源
当我尝试访问 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 documentation页面也会呈现。
项目结构
├── 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'))
]
settings.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 conf文件
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
时浏览器输出**
解决方法
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进行身份验证。为此,请查看third party packages。
并查看Django Vue Auth Demo,以讨论使用分离的前端通过REST进行身份验证时的一些常见错误和陷阱。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。