質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Gunicorn

Gunicorn (Green Unicorn)は、Rubyのunicornをベースに開発されたUNIX向けのPython製HTTPサーバです。他のライブラリとの依存関係がないため、容易にインストールして使用できます。

Django

DjangoはPythonで書かれた、オープンソースウェブアプリケーションのフレームワークです。複雑なデータベースを扱うウェブサイトを開発する際に必要な労力を減らす為にデザインされました。

nginx

nginixは軽量で高性能なwebサーバーの1つです。BSD-likeライセンスのもとリリースされており、あわせてHTTPサーバ、リバースプロキシ、メールプロキシの機能も備えています。MacOSX、Windows、Linux、上で動作します。

Ubuntu

Ubuntuは、Debian GNU/Linuxを基盤としたフリーのオペレーティングシステムです。

Q&A

0回答

274閲覧

【Django】デプロイ後の「Internal Server Error」について

Sylph

総合スコア2

Gunicorn

Gunicorn (Green Unicorn)は、Rubyのunicornをベースに開発されたUNIX向けのPython製HTTPサーバです。他のライブラリとの依存関係がないため、容易にインストールして使用できます。

Django

DjangoはPythonで書かれた、オープンソースウェブアプリケーションのフレームワークです。複雑なデータベースを扱うウェブサイトを開発する際に必要な労力を減らす為にデザインされました。

nginx

nginixは軽量で高性能なwebサーバーの1つです。BSD-likeライセンスのもとリリースされており、あわせてHTTPサーバ、リバースプロキシ、メールプロキシの機能も備えています。MacOSX、Windows、Linux、上で動作します。

Ubuntu

Ubuntuは、Debian GNU/Linuxを基盤としたフリーのオペレーティングシステムです。

0グッド

0クリップ

投稿2023/05/13 20:30

編集2023/05/17 11:24

実現したいこと

ドメインでDjangoのアプリが見れるようにしたい。

目的

ローカルで開発を行ったシステムを本番環境に移行して運用するため。

発生している問題

仮想環境に入った状態でcurlコマンドを送ったところ、ページにエラーが表示されました。
サーバー構築は初めてなので、皆さんの色々なアドバイスを頂ければと思います。

bash

1(djangovenv) root@hostname:/var/www/domain/html/djangovenv/project$ curl --unix-socket /run/gunicorn.sock localhost 2<html> 3 <head> 4 <title>Internal Server Error</title> 5 </head> 6 <body> 7 <h1><p>Internal Server Error</p></h1> 8 9 </body> 10</html> 11 12# こちらは通っています 13adminvps@hostname:~$ curl -I "http://localhost/" 14HTTP/1.1 200 OK 15Server: nginx/1.18.0 (Ubuntu) 16Date: Tue, 16 May 2023 16:06:35 GMT 17Content-Type: text/html 18Content-Length: 612 19Last-Modified: Fri, 21 Apr 2023 06:36:26 GMT 20Connection: keep-alive 21ETag: "64422eea-264" 22Accept-Ranges: bytes 23 24# こちらも通っています 25adminvps@hostname:~$ curl localhost(もしくはhttp://サーバーIPアドレス/) 26<!DOCTYPE html> 27<html> 28<head> 29<title>Welcome to nginx!</title> 30<style> 31 body { 32 width: 35em; 33 margin: 0 auto; 34 font-family: Tahoma, Verdana, Arial, sans-serif; 35 } 36</style> 37</head> 38<body> 39<h1>Welcome to nginx!</h1> 40<p>If you see this page, the nginx web server is successfully installed and 41working. Further configuration is required.</p> 42 43<p>For online documentation and support please refer to 44<a href="http://nginx.org/">nginx.org</a>.<br/> 45Commercial support is available at 46<a href="http://nginx.com/">nginx.com</a>.</p> 47 48<p><em>Thank you for using nginx.</em></p> 49</body> 50</html>

参考1(systemdサービスファイル)

gunicorn.service

1# アプリ名を「sample」としています 2[Unit] 3Description=gunicorn daemon 4Requires=gunicorn.socket 5After=network.target 6[Service] 7User=adminvps 8Group=root 9WorkingDirectory=/var/www/sample.com/html/djangovenv/project 10ExecStart=/var/www/sample.com/html/djangovenv/bin/gunicorn --workers 3 --bind unix:/run/gunicorn.sock sample.wsgi:application 11[Install] 12WantedBy=multi-user.target

参考2(Gunicorn Socketファイル)

gunicorn.socket

1[Unit] 2Description=gunicorn socket 3[Socket] 4ListenStream=/run/gunicorn.sock 5[Install] 6WantedBy=sockets.target

参考3(サービスの状態確認)

bash

1# アプリ名を「sample」としています 2(djangovenv) root@hostname:/var/www/sample.com/html/djangovenv/project# systemctl status sample 3● gunicorn.service - gunicorn daemon 4 Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled) 5 Active: active (running) since Sun 2023-05-14 04:09:21 JST; 4s ago 6TriggeredBy: ● gunicorn.socket 7 Main PID: 7419 (gunicorn) 8 Tasks: 4 (limit: 1026) 9 Memory: 112.0M 10 CPU: 1.148s 11 CGroup: /system.slice/gunicorn.service 12 ├─7419 /var/www/sample.com/html/djangovenv/bin/python3 /var/www/sample.com/html/djangovenv/bin/gunicorn --workers 3> 13 ├─7420 /var/www/sample.com/html/djangovenv/bin/python3 /var/www/domain/html/djangovenv/bin/gunicorn --workers 3> 14 ├─7421 /var/www/sample.com/html/djangovenv/bin/python3 /var/www/sample.com/html/djangovenv/bin/gunicorn --workers 3> 15 └─7422 /var/www/sample.com/html/djangovenv/bin/python3 /var/www/sample.com/html/djangovenv/bin/gunicorn --workers 3> 16May 14 04:09:21 hostname systemd[1]: Started gunicorn daemon. 17May 14 04:09:21 hostname gunicorn[7419]: [2023-05-14 04:09:21 +0900] [7419] [INFO] Starting gunicorn 20.1.0 18May 14 04:09:21 hostname gunicorn[7419]: [2023-05-14 04:09:21 +0900] [7419] [INFO] Listening at: unix:/run/gunicorn.sock (7419) 19May 14 04:09:21 hostname gunicorn[7419]: [2023-05-14 04:09:21 +0900] [7419] [INFO] Using worker: sync 20May 14 04:09:21 hostname gunicorn[7420]: [2023-05-14 04:09:21 +0900] [7420] [INFO] Booting worker with pid: 7420 21May 14 04:09:21 hostname gunicorn[7421]: [2023-05-14 04:09:21 +0900] [7421] [INFO] Booting worker with pid: 7421 22May 14 04:09:21 hostname gunicorn[7422]: [2023-05-14 04:09:21 +0900] [7422] [INFO] Booting worker with pid: 7422 23lines 1-21/21 (END)

参考3(settings.py)

py

1from pathlib import Path 2import os 3 4BASE_DIR = Path(__file__).resolve().parent.parent 5SECRET_KEY = 'django-insecure-○○=○○' 6DEBUG = True 7ALLOWED_HOSTS = ['localhost', 'サーバーIPアドレス', 'ドメイン名', 'www.ドメイン名'] 8 9LOGGING = { 10 'version': 1, 11 'disable_existing_loggers': False, 12 'handlers': { 13 'file': { 14 'level': 'DEBUG', 15 'class': 'logging.FileHandler', 16 'filename': './app.log', 17 }, 18 'console': { 19 'class': 'logging.StreamHandler', 20 }, 21 }, 22 'loggers': { 23 'django': { 24 'handlers': ['file'], 25 'level': 'DEBUG', 26 'propagate': True, 27 }, 28 }, 29} 30 31INSTALLED_APPS = [ 32 'accounts.apps.AccountsConfig', 33 'django.contrib.admin', 34 'django.contrib.auth', 35 'django.contrib.contenttypes', 36 'django.contrib.sessions', 37 'django.contrib.messages', 38 'django.contrib.staticfiles', 39 'bootstrap4', 40] 41 42BOOTSTRAP4 = { 43 'include_jquery': True, 44} 45 46MIDDLEWARE = [ 47 'django.middleware.security.SecurityMiddleware', 48 'django.contrib.sessions.middleware.SessionMiddleware', 49 'django.middleware.common.CommonMiddleware', 50 'django.middleware.csrf.CsrfViewMiddleware', 51 'django.contrib.auth.middleware.AuthenticationMiddleware', 52 'django.contrib.messages.middleware.MessageMiddleware', 53 'django.middleware.clickjacking.XFrameOptionsMiddleware', 54] 55 56ROOT_URLCONF = 'sample.urls' 57TEMPLATES = [ 58 { 59 'BACKEND': 'django.template.backends.django.DjangoTemplates', 60 'DIRS': [os.path.join(BASE_DIR, 'templates')], 61 'APP_DIRS': True, 62 'OPTIONS': { 63 'context_processors': [ 64 'django.template.context_processors.media', 65 'django.template.context_processors.debug', 66 'django.template.context_processors.request', 67 'django.contrib.auth.context_processors.auth', 68 'django.contrib.messages.context_processors.messages', 69 ], 70 'builtins':[ 71 'bootstrap4.templatetags.bootstrap4', 72 ], 73 }, 74 }, 75] 76 77WSGI_APPLICATION = 'sample.wsgi.application' 78DATABASES = { 79 'default': { 80 'ENGINE': 'django.db.backends.mysql', 81 'NAME': 'sample_db', 82 'USER': 'root', 83 'PASSWORD': '********', 84 'HOST': 'localhost', 85 'PORT': '3306', 86 'OPTIONS': { 87 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", 88 }, 89 } 90} 91 92PASSWORD_HASHERS = [ 93 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 94 'django.contrib.auth.hashers.BCryptPasswordHasher', 95 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 96 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 97] 98 99AUTH_USER_MODEL = 'accounts.User' 100AUTH_PASSWORD_VALIDATORS = [ 101 { 102 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 103 }, 104 { 105 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 106 }, 107 { 108 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 109 }, 110 { 111 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 112 }, 113] 114 115LANGUAGE_CODE = 'ja' 116TIME_ZONE = 'Asia/Tokyo' 117USE_I18N = True 118USE_TZ = True 119USE_L10N = False 120 121from django.conf.global_settings import DATETIME_INPUT_FORMATS 122DATETIME_INPUT_FORMATS += ('%Y/%m/%d',) 123STATIC_URL = '/static/' 124STATICFILES_DIRS = [ 125 os.path.join(BASE_DIR, 'accounts/static'), 126] 127STATIC_ROOT = '/var/www/sample.com/html/static_for_deploy' 128 129# media root setting 130MEDIA_URL = '/media/' 131MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') 132 133LOGIN = '/accounts/login' 134LOGIN_REDIRECT_URL = '/app' 135LOGOUT_REDIRECT_URL = '/accounts/login'

エラーの詳細

app.log

1Invalid HTTP_HOST header: 'ドメイン名'. You may need to add 'ドメイン名' to ALLOWED_HOSTS. 2Traceback (most recent call last): 3 File "/var/www/sample.com/html/djangovenv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner 4 response = get_response(request) 5 File "/var/www/sample.com/html/djangovenv/lib/python3.10/site-packages/django/utils/deprecation.py", line 133, in __call__ 6 response = self.process_request(request) 7 File "/var/www/sample.com/html/djangovenv/lib/python3.10/site-packages/django/middleware/common.py", line 48, in process_request 8 host = request.get_host() 9 File "/var/www/sample.com/html/djangovenv/lib/python3.10/site-packages/django/http/request.py", line 167, in get_host 10 raise DisallowedHost(msg) 11django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: 'ドメイン名'. You may need to add 'ドメイン名' to ALLOWED_HOSTS.

↑「ALLOWED_HOSTS」は空にしていないのに何故でしょうか・・・

補足情報(FW/ツールのバージョンなど)

Ubuntu 22.04
さくらのVPS
仮想2Core
1GBメモリ

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

AbeTakashi

2023/05/14 10:14

Internal Server Error(500エラー)の原因は多岐にわたるので、第三者が簡単にアドバイスすることは難しいかと思います。とりあえずエラーログを見て原因を突き止めていくしかないかと。ログが出てない場合は出るように設定されるといいかと思います。 参考) https://qiita.com/gunkan8mmt/items/b11f54996e6dbe091a82
Sylph

2023/05/16 18:35

AbeTakashi様、上記を参考にエラーログを出せるようにしました。 Invalid HTTP_HOST header: 'ドメイン名'. You may need to add 'ドメイン名' to ALLOWED_HOSTS. Traceback (most recent call last): File "/var/www/サイトフォルダ名/html/djangovenv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/var/www/サイトフォルダ名/html/djangovenv/lib/python3.10/site-packages/django/utils/deprecation.py", line 133, in __call__ response = self.process_request(request) File "/var/www/サイトフォルダ名/html/djangovenv/lib/python3.10/site-packages/django/middleware/common.py", line 48, in process_request host = request.get_host() File "/var/www/サイトフォルダ名/html/djangovenv/lib/python3.10/site-packages/django/http/request.py", line 167, in get_host raise DisallowedHost(msg) django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: 'ドメイン名'. You may need to add 'ドメイン名' to ALLOWED_HOSTS. ※上記エラーは「受け取ったサイト名とDjangoで設定しているサイト名が異なる」という意味のようですが、settings.pyには予め「ALLOWED_HOSTS = ['IPアドレス', 'ドメイン名', 'www.ドメイン名']」が設定されています※
AbeTakashi

2023/05/17 02:06

↑の内容は質問文に追記されるといいかと思います。ここに書いても読まない人が多いかと思います。 たしかにALLOWED_HOSTSのエラーのように見えますが(ただ、この場合500エラーになるのかな?という疑問もありますが。普通なら403エラーになりそうな気がする)、動作環境や設定内容の詳細が質問文内に記載されてないので第三者が原因を特定するのが難しいように思えます。 参考) https://yu-nix.com/archives/django-allowed-hosts/ などのドキュメントを参考にして、まずはご自身で色々検証してみるしかないと思います。難しいようであれば出せるギリギリの範囲まで情報を追記されると回答が出てくるかもしれません(ここに書かずに質問文に追記してください。)。
AbeTakashi

2023/05/17 13:29

とりあえず ALLOWED_HOSTS を '*' (ワイルドカード)にしてみるなどして、ご自身の環境で色々試してみて検証するしかないと思いますよ。第三者がその環境を同じように再現できないので、具体的なアドバイスは出にくい状況かと思いますので。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問