1. 切换到服务器存放项目目录
cd /data/www
2. 使用scp或者借助git工具将项目引入目录
以git为例
git clone git@xxx.com
3. 安装Django项目虚拟环境和依赖
cd /data/www/myprojectpython3 -m venv venvsource venv/bin/activatepip3 install -r requirements.txt
4. 收集Django静态文件
mkdir staticmkdir staticfilespython3 manage.py collectstatic
执行该命令前,确保setting.py中配置了
STATIC_URL = '/static/'# 开发阶段放置项目自己的静态文件STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)# 执行collectstatic命令后会将项目中的静态文件收集到该目录下面来(所以不应该在该目录下面放置自己的一些静态文件,因为会覆盖掉)STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
5. 启动项目, 检查项目是否运行正常
开启服务器8000端口后,运行项目在8000端口(8000端口并非固定, 可自行定义)
python3 manage.py runserver 0.0.0.0:8000
访问http://服务器公网IP:8000查看服务器Django项目是否启动, 启动正常继续
6. 安装uWSGI
pip3 install uwsgi
确保在venv下安装哦
7. 创建并写入uWSGI配置文件
mkdir uwsgicd uwsgitouch uwsgi.ini uwsgi.log uwsgi.pid uwsgi.statusvim uwsgi.ini
uwsgi.ini内容参考以下
[uwsgi]uid = rootgid = root# plugin = python, http# env = DJANGO_PRODUCTION_SETTINGS=TRUEchdir = /data/www/myprojectmodule = myproject.wsgi# logto=%(chdir)/uwsgi/uwsgi.logmaster = Trueprocesses = 4listen = 128http = :8000vaccum = Truestatic-map = /static=%(chdir)/staticstats=%(chdir)/uwsgi/uwsgi.statuspidfile=%(chdir)/uwsgi/uwsgi.piddaemonize = %(chdir)/uwsgi/uwsgi.log
8. 通过uWSGI启动项目
cd /data/www/myprojectuwsgi --ini uwsgi/uwsgi.ini (启动之前先确保在venv环境中)
9. 通过上述验证方法检查项目启动正常后,配置Nginx转发
nignx 目录 /etc/nginx/conf.d 用项目的访问网址命名 nginx 文件,比如 myproject.com.conf
server {listen 80;server_name myproject.site.com;location / {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_pass http://127.0.0.1:8000;}location ^~ /static/ {proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;client_max_body_size 10M;proxy_set_header X-Forwarded-Host $host;proxy_set_header X-Forwarded-Server $host;proxy_http_version 1.1;proxy_request_buffering off;proxy_pass http://127.0.0.1:8000;}location ~ ^/media {root /data/www/myproject/media;}access_log /data/logs/www/myproject.site.com.log;}
10. 重启nginx
/etc/init.d/nginx restart
或者
service nginx reload|restart
或者
systemctl reload|restart nginx.service
11. 可能用的命令
# 退出虚拟环境venvdeactivate# 查看8000端口进程netstat -lnp|grep 8000# 终止进程kill -9 xxxx# 新建命令窗口screen -S windowname# 查看nginx配置目录locate nginx.conf
