---
# System prepended metadata

title: 在ubuntu架設django

---

* 1.ubuntu版本：20
* 2.postgresql:12
* 3.django版本：4https://hackmd.io/
* 4.gunicorn:21.2.0 

資料庫的安裝
1.sudo apt update

2.sudo apt install postgresql postgresql-contrib

3.sudo systemctl status postgresql

4.sudo -u postgres psql

5.ALTER USER postgres WITH PASSWORD 'your_password';

6.CREATE DATABASE nfvpap;

7.\q

8./etc/postgresql/{version}/main/postgresql.conf

9.listen_addresses = '*'

10.sudo systemctl restart postgresql



系統部署
1.
sudo apt-get update && sudo apt-get upgrade -y

2.
sudo apt-get install python3-venv

3.
開啟python虛擬環境

4.
pip3 install gunicorn

5.
sudo vim /etc/systemd/system/gunicorn.socket

6.
```
[Unit]
Description=gunicorn socket
[Socket]
ListenStream=/run/gunicorn.sock
[Install]
WantedBy=sockets.target
```

7.
which gunicorn

8.
sudo vim /etc/systemd/system/gunicorn.service

9.
```
[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target
[Service]
User=<youruser> # 此處輸入這台機器的使用者名
Group=www-data
WorkingDirectory=<path/to/yourprojectdir> # 輸入Django專案的路徑
ExecStart=<gunicorn_path> \   # 輸入gunicorn的路徑
          --access-logfile - \
          --workers 3 \
          --bind unix:/run/gunicorn.sock \
          <yourproject>.wsgi:application
[Install]
WantedBy=multi-user.target
```
10.
sudo systemctl start gunicorn.socket
sudo systemctl enable gunicorn.socket

11.
sudo systemctl status gunicorn.socket

12.
file /run/gunicorn.sock

13.
sudo journalctl -u gunicorn.socket

14.
sudo systemctl status gunicorn

15.
curl ---unix-socket /run/gunicorn.sock localhost

16.
sudo journalctl -u gunicorn --since today

17.
sudo systemctl daemon-reload
sudo systemctl restart gunicorn

18.
sudo vim /etc/nginx/sites-available/project_name.conf

19.
```
server {
    listen 80;
    server_name <domain_name> <server_ip>; # 此處輸入網域名及ip，兩者以空格隔開。    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root <your_static_root_path>; # static的根目錄位置
    }location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }
}
```

20.
```
sudo ln -s /etc/nginx/sites-available/project_name.conf /etc/nginx/sites-enabled
sudo nginx -t
sudo systemctl restart nginx
```

Q/A
如果iframe嵌入檔案的那個頁面被封鎖記得加入
![圖片](https://hackmd.io/_uploads/HkFGgtOEC.png)

mysql時區問題
sudo mysql_tzinfo_to_sql /usr/share/zoneinfo | sudo mysql -u root -p

https://medium.com/tsungs-blog/django-%E5%9C%A8ubuntu%E4%B8%AD%E9%81%8B%E7%94%A8nginx-gunicorn-%E6%9E%B6%E8%A8%AD-django-api-server-6d41c165a2c7

https://akebee.com/django-deploy-nginx/