用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