# AWS(Lightsail)+Django+Gunicorn+Nginx+Supervisor網站建置筆記
###### tags: `Lightsail` `Django` `Nginx`
## AWS-Lightsail
選擇Instance地點,這邊選擇日本
然後選擇Linux+Django的組合

並命名

建立之後要等一下
然後點選紅圈處可以進行連線

Networking那邊記得加TCP(8000)
## Django/Gunicorn
在Lightsail裡面創立我們要的資料夾
```
cd htdocs
mkdir wensite
cd wensite
mkdir static
cd static
mkdir css
cd ..
mkdir templates
```
創立一個虛擬環境
```
python3 -m venv env
```
接著使用這裡面的python與安裝django、gunicorn
```
source env/bin/activate
python -m pip install django
pip install gunicorn
```
創建專案與app
```
django-admin startproject wensite .
python manage.py startapp homepage
```
將homepage/view.py檔案內增加
```
def home(request):
return render(request, 'test.html',{'data':''})
```
將原先urls.py檔案內的
```
urlpatterns = [
path('admin/', admin.site.urls),
]
```
改成
```
urlpatterns = [
path('admin/', admin.site.urls),
path('', home),
url(r'^static/(?P<path>.*)$', static.serve, {'document_root': settings.STATIC_ROOT}, name='static'),
]
```
將原先setting.py檔案內
加上import os
BASE_DIR改成```os.path.dirname(os.path.dirname(os.path.abspath(__file__)))```
DEBUG改False
ALLOWED_HOSTS填入Public IP或你的網址
INSTALLED_APPS加上'homepage',
templates改
```
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates').replace('\\', '/')],
'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',
],
},
},
]
```
database改
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
```
TIME_ZONE改'Asia/Taipei'
加上STATIC_ROOT = os.path.join(BASE_DIR, 'static')
新增gunicorn.conf.py檔案
加入
```
import os
bind = '0.0.0.0:8000'
```
## Nginx
安裝
```
sudo apt-get install nginx
```
修改/etc/profile
在
export PATH前增加
PATH=$PATH:/etc/nginx
/etc/nginx/sites-available/default這邊
server_name 改你的網址
加
```
location /static {
root /home/bitnami/htdocs/wensite/static;
}
```
改完restart
```
sudo service nginx restart
```
## Supervisor
安裝
```
sudo apt-get install supervisor
```
```
cd /etc/supervisor/conf.d/
```
加入wensite.conf
```
[group:wensite]
programs=site
[program:site]
directory=/home/bitnami/htdocs/wensite
command=/home/bitnami/htdocs/wensite/env/bin/gunicorn -c gunicorn.conf.py wensite.wsgi:application
environment=PATH="/home/bitnami/htdocs/wensite/env/bin/"
user = root
autostart=true
autorestart=true
stdout_logfile=/home/bitnami/supervisor.log
```
輸入
```
sudo supervisorctl reread
sudo supervisorctl reload
sudo supervisorctl status
```
看看wensite:site有沒有處於RUNNING狀態
有的話Terminal視窗關掉網站也可以繼續運作!!
主要參考文章:
[Django Tutorial in Visual Studio Code](https://code.visualstudio.com/docs/python/tutorial-django)
[Django + Gunicorn + Nginx 部署之路](https://www.cnblogs.com/hippieZhou/p/11488514.html)
[Django Tutorial for Programmers: 25. Deploy to Ubuntu Server](https://ithelp.ithome.com.tw/articles/10161146)