momo's Blog.

使用容器部署前后端分离的Django应用

字数统计: 345阅读时长: 1 min
2021/11/01 Share

前言

在前后端分离或者多语言集成的项目中, 一般都需要独立的环境编译打包. 那么如果依照传统的构建方式, 在一个容器中进行打包构建, 那么会造成容器镜像层的冗余, 不仅体积大, 而且容器内置多种环境也不安全.

部署

WSGI

Django 一般采用的是 WSGI 部署

  • deploy/uwsgi_conf.ini
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    [uwsgi]
    chdir = /home/backend
    module = opsbackend.wsgi:application
    socket = 127.0.0.1:8000
    master = true

    # 以上4个是核心配置项

    #vhost = true //多站模式
    #no-site = true //多站模式时不设置入口模块和文件
    workers = 8
    #reload-mercy = 10
    vacuum = true
    max-requests = 1000
    limit-as = 512
    buffer-size = 30000
    #pidfile = /var/run/uwsgi.pid //pid文件,用于下脚本启动、停止该进程
    disable-logging = true

ASGI

因为我们项目使用了channel做长连接, 所以也需要部署一个ASGI的服务器

安装

1
python -m pip install daphne

启动

1
daphne -p 990 opsbackend.asgi:application

Nginx

我们前端使用Nginx托管

配置文件

deploy/default.conf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
server {
listen 80;

listen [::]:80;


location / {
include uwsgi_params;
uwsgi_pass 127.0.0.1:8000;
}

location /static {
alias /home/backend/static/static;
}

location ^~ /ws {
proxy_pass http://channels-backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
}
}

使用多阶段构建

项目结构

1
2
3
4
5
6
./opstools/
├── backend # 后端代码
├── deploy # 部署目录
├── Dockerfile
├── frontend # 前端代码
└── README.md
CATALOG
  1. 1. 前言
  2. 2. 部署
    1. 2.1. WSGI
    2. 2.2. ASGI
      1. 2.2.1. 安装
      2. 2.2.2. 启动
    3. 2.3. Nginx
      1. 2.3.1. 配置文件
  3. 3. 使用多阶段构建
    1. 3.1. 项目结构