使用 SQLite3, Nginx, Gunicorn 在 Ubuntu 1604 上部署 Django

时间:2022-06-26 05:24:37

参考文章:
https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04


1. 安装 Python3 和 Ngnix
$ sudo apt-get update
$ sudo apt-get install python3-pip python3-dev nginx


2. 设置 Python 虚拟环境
2.1 安装 virtualenv
$ sudo -H pip3 install virtualenv
2.2 创建虚拟环境
$ mkdir ~/myproject
$ cd ~/myproject
$ virtualenv myprojectenv
2.3 激活虚拟环境
$ source myprojectenv/bin/activate
2.4 安装 Django, Gunicorn
$ pip install django gunicorn


3. 配置 Django
3.1 上传本地 Django 文件夹到服务器 myproject 目录
3.2 修改 Django setting.py 文件
$ nano ~/myproject/myproject/settings.py
settings.py
ALLOWED_HOSTS = ['your_server_domain_or_IP', 'second_domain_or_IP', . . .]
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
3.3 搜集静态文件
$ ~/myproject/manage.py collectstatic
3.4 添加端口 8000 防火墙规则
$ sudo ufw allow 8000
3.5 测试 Gunicorn 
$ gunicorn --bind 0.0.0.0:8000 myproject.wsgi
3.6 停止虚拟环境
$ deactivate


4. 创建 Gunicorn systemd 服务文件
4.1 创建文件
$ sudo nano /etc/systemd/system/gunicorn.service
/etc/systemd/system/gunicorn.service
[Unit]
Description=gunicorn daemon
After=network.target
[Service]
User=sammy
Group=www-data
WorkingDirectory=/home/sammy/myproject
ExecStart=/home/sammy/myproject/myprojectenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/sammy/myproject/myproject.sock myproject.wsgi:application
[Install]
WantedBy=multi-user.target
4.2 启动服务,添加到开机
$ sudo systemctl start gunicorn
$ sudo systemctl enable gunicorn


5. 配置 Nginx 
5.1 配置文件
$ sudo nano /etc/nginx/sites-available/myproject
/etc/nginx/sites-available/myproject
server {
    listen 80;
    server_name server_domain_or_IP;


    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/sammy/myproject;
    }


    location / {
        include proxy_params;
        proxy_pass http://unix:/home/sammy/myproject/myproject.sock;
    }
}
5.2 文件链接到sites-enabled目录来启用该文件
$ sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled
5.3 重启 Nginx 服务
$ sudo systemctl restart nginx
5.4 设置防火墙
$ sudo ufw allow 'Nginx Full'


至此,配置完成。