Django項目部署到Ubuntu服務器

1.将DjanGo项目配置文件中的 ALLOWED_HOSTS设置为:当前服务器IP或*:

ALLOWED_HOSTS = ["*",]

2.uwsgi

a.在服務器安裝uwsgi

pip install uwsgi

b.測試uwsgi

創建一個test.py文件,寫入代碼:

def application(env, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    return [b"Hello World"]

在服務器上執行代碼:

uwsgi --http :8001 --wsgi-file test.py

输出以下内容代表uwsgi安装成功:

*** Starting uWSGI 2.0.19.1 (64bit) on [Fri Dec 11 22:13:49 2020] ***
compiled with version: 4.8.5 on 03 December 2020 09:20:55
os: Linux-4.15.0-118-generic #119-Ubuntu SMP Tue Sep 8 12:30:01 UTC 2020
nodename: VM-0-7-ubuntu
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 1
current working directory: /home/ubuntu/web/mysite
detected binary path: /home/ubuntu/anaconda3/bin/uwsgi
*** WARNING: you are running uWSGI without its master process manager ***
your processes number limit is 7086
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uWSGI http bound on :8000 fd 4
spawned uWSGI http 1 (pid: 17524)
uwsgi socket 0 bound to TCP address 127.0.0.1:40259 (port auto-assigned) fd 3
Python version: 3.7.6 (default, Jan  8 2020, 19:59:22)  [GCC 7.3.0]
*** Python threads support is disabled. You can enable it with --enable-threads ***
Python main interpreter initialized at 0x200ef00
your server socket listen backlog is limited to 100 connections
your mercy for graceful operations on workers is 60 seconds
mapped 72920 bytes (71 KB) for 1 cores
*** Operational MODE: single process ***
WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0x200ef00 pid: 17523 (default app)
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI worker 1 (and the only) (pid: 17523, cores: 1)

c. django程序使用uwsgi

uwsgi --http :8001 --wsgi-file firstsite/wsgi.py --master --processes 4

配置文件启动uwsgi

创建uwsgi.ini文件,写入:

[uwsgi]
# Http通信方式的IP地址:端口號(不使用nginx,可以通過瀏覽器直接訪問)
# http = :8001
# 套接字方式的IP地址:端口號(需要映射到nginx),此端口必須與後面的Nginx一致
socket = 0.0.0.0:8001
# chdir:項目工作的絕對路徑
chdir = /home/ubuntu/web/mysite
# 項目中wsgi.py文件目錄
wsgi-file = firstsite/wsgi.py
# 進程數
processes = 4
# 每個進程的線程數
threads = 1
# 是否開啟管理員進程
master = true
# 服務的PID記錄文件
pidfile = /home/ubuntu/web/mysite/uwsgi.pid
# 服務的日誌文件位置
daemonizer = /home/ubuntu/web/mysite/uwsgi.log

根据配置文件启动uwsgi

uwsgi --ini uwsgi.ini

查看uwsgi是否启动成功:

ps aux | grep uwsgi

d. uwsgi启动太多次

your processes number limit is 16384
your memory page size is 4096 bytes
detected max file descriptor number: 65536
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
probably another instance of uWSGI is running on the same address (:8080).
bind(): Address already in use [core/socket.c line 769]

可以用命令杀掉这个端口在重启:

sudo fuser -k 8080/tcp

e. 收集djiango静态文件

在django的配置文件末尾添加:

import os
STATIC_ROOT = os.path.join(BASE_DIR, "static")

执行 python manage.py collectstatic 命令,django项目所有相关的静态文件都会收集到static目录。

f. 項目有更新,需重新運行uwsgi服務

uwsgi --stop uwsgi.pid
uwsgi --ini uwsgi.ini

3. Nginx

a. 安裝Nginx

apt-get install nginx

b. vim打開/etc/nginx/nginx.conf,寫入:


user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;
 
events {
	worker_connections 768;
	# multi_accept on;
}
 
http {
	server {
		listen      8888;
		server_name **.**.***.***;       #这里填你主机的公网IP
		charset     utf-8;
		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 20m;    #允许客户端请求的最大单文件字节数
		client_body_buffer_size 128k;  #缓冲区代理缓冲用户端请求的最大字节数,
		proxy_connect_timeout 1 ;  #nginx跟后端服务器连接超时时间(代理连接超时)
		proxy_send_timeout 10;        #后端服务器数据回传时间(代理发送超时)
		proxy_read_timeout 10;         #连接成功后,后端服务器响应时间(代理接收超时)
		proxy_buffer_size 4k;             #设置代理服务器(nginx)保存用户头信息的缓冲区大小
		proxy_buffers 4 32k;               #proxy_buffers缓冲区,网页平均在32k以下的话,这样设置
		proxy_busy_buffers_size 64k;    #高负荷下缓冲大小(proxy_buffers*2)
		proxy_temp_file_write_size 64k;  #设定缓存文件夹大小,大于这个值,将从upstream服务器传
  
	# 媒体文件目录(MP4,MP3等用户上传的数据,如果没有可以不写)
    location /media  {
        alias /yajun/media;    #你的media文件路径
    }
  # 静态文件目录(js,css等)
    location /static {
        alias /yajun/static;     #你的static文件路径
    }
    # 项目文件路径
    location / {
        uwsgi_pass  0.0.0.0:8001;   #这里与uwsgi一致
        include     /etc/nginx/uwsgi_params;
        uwsgi_read_timeout 50;
        # try_files $uri $uri/ =404;
    }
}
 
 
	##
	# Basic Settings
	##
 
	sendfile on;
	tcp_nopush on;
	tcp_nodelay on;
	keepalive_timeout 65;
	types_hash_max_size 2048;
	# server_tokens off;
 
	# server_names_hash_bucket_size 64;
	# server_name_in_redirect off;
 
	include /etc/nginx/mime.types;
	default_type application/octet-stream;
 
	##
	# SSL Settings
	##
 
	ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
	ssl_prefer_server_ciphers on;
 
	##
	# Logging Settings
	##
 
	access_log /var/log/nginx/access.log;
	error_log /var/log/nginx/error.log;
 
	##
	# Gzip Settings
	##
 
	gzip on;
 
	# gzip_vary on;
	# gzip_proxied any;
	# gzip_comp_level 6;
	# gzip_buffers 16 8k;
	# gzip_http_version 1.1;
	# gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
 
	##
	# Virtual Host Configs
	##
 
	#include /etc/nginx/conf.d/*.conf;
	#include /etc/nginx/sites-enabled/*;
}
 
 
#mail {
#	# See sample authentication script at:
#	# http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
# 
#	# auth_http localhost/auth.php;
#	# pop3_capabilities "TOP" "USER";
#	# imap_capabilities "IMAP4rev1" "UIDPLUS";
# 
#	server {
#		listen     localhost:110;
#		protocol   pop3;
#		proxy      on;
#	}
# 
#	server {
#		listen     localhost:143;
#		protocol   imap;
#		proxy      on;
#	}
#}

c. 重啟Nginx服務

service nginx restart

 NGinx重啟報錯:Job for nginx.service failed. See 'systemctl status nginx.service' and 'journalctl -xn' fo

1.執行systemctl status nginx.service 查看報錯原因; systemctl stasus nginx.service -l 查看錯誤詳情。

2.nginx配置文件錯誤:nginx -t 進行查看修改。

3. netstat -tnlp查看網絡狀態,端口是否被佔用。

4. ps -ef | grep 80 ,查看佔用80端口程序。

5.檢查nginx是否已經啟動: ps -aux | grep nginx;如果已經啟動可以使用命令殺掉: pkill -9 nginx

4.Finally

打開本地瀏覽器訪問http://**.**.**.**:8888/(**.**.**.**是你的公網ip),就可以看見你的項目了。

 

參考文章:

https://blog.csdn.net/qq_29269161/article/details/106922512

 

你可能感兴趣的:(nginx,linux,django)