此项目部署采用uwsgi+nginx+djagno,首先先确保python、mysql、redis、nginx等都已在服务器安装完毕,具体安装步骤就不再详细说明。
安装虚拟环境
pip install virtualenv
新建虚拟环境
mkvirtualenv xxx
进入虚拟环境
workon xxx
然后将requirements.txt文件上传到服务器之后运行:
pip install -r requirements.txt # 安装依赖包
安装uwsgi
pip install uwsg
我的项目文件目录是这样的,下面都是直接以此项目为例进行部署。
uwsgi --http :8000 --module Onteac.wsgi
运行成功后可以通过:
http://ip:端口号
能访问到项目,说明uwsgi和项目都是没有问题的。但是这时候的静态文件样式是不生效的
# the upstream component nginx needs to connect to
upstream django {
server 127.0.0.1:8000; # for a web port socket (we'll use this first)
}
# configuration of the server
server {
# the port your site will be served on
listen 80;
# the domain name it will serve for
server_name 118.31.61.2; # 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 /home/hzy/onteach/media; # 指向django的media目录
}
location /static {
alias /home/hzy/onteach/teach_static; # 指向django的static目录
}
# Finally, send all non-media requests to the Django server.
location / {
uwsgi_pass django;
include uwsgi_params; # the uwsgi_params file you installed
}
}
sudo ln -s /home/hzy/onteach/conf/nginx/uc_nginx.conf /etc/nginx/conf.d/
STATIC_ROOT = os.path.join(BASE_DIR, "teach_static/")
注意:这里的文件STATIC_ROOT的名称是项目部署时收集静态文件用的,名字不要和STATICFILES_DIRS的文件名一样
运行命令
python manage.py collectstatic
sudo /usr/sbin/nginx
这里需要注意是直接用nginx命令启动, 不要用systemctl启动nginx不然会有权限问题
[uwsgi]
# Django-related settings
# the base directory (full path)
chdir = /home/hzy/onteach
# Django's wsgi file
module = Onteach.wsgi
# the virtualenv (full path)
# process-related settings
# master
master = true
# maximum number of worker processes
processes = 10
# the socket (use the full path to be safe
socket = 127.0.0.1:8000
# ... with appropriate permissions - may be needed
# chmod-socket = 664
# clear environment on exit
vacuum = true
virtualenv = /home/hzy/.virtualenvs/teach_env
# logto = /tmp/mylog.log
chdir: 表示需要操作的目录,也就是项目的目录
module: wsgi文件的路径
processes: 进程数
virtualenv:虚拟环境的目录
workon teach_env
uwsgi -i home/hzy/onteach/conf/uwsgi.ini
部署完成后,nginx会监听80端口,所以不用再输入端口号,直接通过ip访问即可,下面是我部署好的项目
http://118.31.61.2/