用Docker部署Django+uWSGI+Nginx
-
大致步骤如下:
-
创建Centos容器
-
安装Python及pip
-
安装MySQL
-
使Django连接到MySQL
-
运行uWSGI服务器
-
运行Nginx服务器
创建Centos容器
安装docker软件
yum install docker
-
创建一个centos容器
docker run -d --name deploy1 --network host centos tail -f /dev/null
-
-d:让它在后台运行。
-
–name deploy1:设置名字。
-
–network host:让它加入宿主机的网络,从而可以连上外网。
-
centos:要运行的镜像。docker会自动从官方镜像中拉取latest版本。
-
tail -f /dev/null:让容器一直执行某条命令,以免没有任务而自动退出。
进入centos容器。
docker exec -it deploy1 bash
-
将Django项目的源代码从宿主机拷贝到centos容器中
docker cp /root/django deploy1: /var/www/web_project
安装Python及pip
yum install epel-release # 添加epel软件库
yum install python34 # 安装指定版本的python
然后用pip安装Django项目需要的Python第三方库。
如果项目目录下有一个requirements.txt,则可以用pip3.4 install -r requirements.txt
安装MySQL
Yum install mariadb
执行 Mysql_secure_installtion进行初始化,设置密码为123456
使Django连接到MySQL
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # 数据库引擎,不用改
'NAME': 'blog', # database名,需要在mysql中已存在
'USER': 'root',
'PASSWORD': '******',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
运行uWSGI服务器
-
安装依赖库:yum install build-essential python-devel
-
安装uWSGI:pip install uwsgi
-
进入Django项目目录,执行mkdir uwsgi,创建一个uwsgi文件夹。再执行vi uwsgi/uwsgi.ini,在其下创建一个uwsgi.ini,作为配置文件。其内容如下:
[uwsgi]
chdir = /var/www/web_project
socket= 127.0.0.1:3301
http = 0.0.0.0:8001
module = web_project.wsgi
#home = /var/www/vitual/
master = true
processes = 5
vacuum = true
daemonize=/var/log/uwsgi.log
使用配置文件启动uWSGI服务器(默认在后台运行):uwsgi --ini uwsgi/uwsgi.ini
运行Nginx服务器
安装Nginx:yum install nginx
修改Nginx的配置文件 /etc/nginx/site-enable/mysite_nginx.conf
upstream django {
server 127.0.0.1:3301; # for a web port socket (we'll use this first)
}
server {
# the port your site will be served on
listen 8081;
# the domain name it will serve for
server_name _; # substitute your machine's IP address or FQDN
charset utf-8;
# max upload size
client_max_body_size 75M; # adjust to taste
# Django media
location /media{
alias /var/www/web_project/media/; # your oDjango project's media files - amend as required
}
location /static {
alias /var/www/web_project/allstatic/; # your Django project's static files - amend as required
}
location /admin {
uwsgi_pass django;
include uwsgi_params; # the uwsgi_params file you installed
}
location /api {
uwsgi_pass django;
include uwsgi_params; # the uwsgi_params file you installed
}
location /ckeditor/upload/ {
proxy_method POST;
proxy_pass http://127.0.0.1:8001$request_uri;
}
location / {
root /var/www/html/dist;
index index.html;
#try_files $uri $uri/ /index.html;
}
}
先启动uWSGI服务器,再用nginx启动nginx服务器(默认作为守护进程运行)
-
数据的持久化
docker run -d -p 80:8081 -p 10000:8001 --restart=always --privileged=true -v /usr/docker_dat/mysql/data:/var/lib/mysql --name newblog5 -p 3306:3306 -e MYSQL_ROOT_PASSWORD=root webblog_4
映射本地的目录到 容器内部的 /var/lib/msyql
-
第一次数据库会报没有权限,需要修改mysql的数据库权限
chown -R mysql /var/lib/mysql