有些新手朋友問我反響代理和負載均衡如何使用,那麼記錄一下nginx基本的負載均衡和反向代理的使用(以python的django框架來簡單介紹一下,django+gunicorn/wsgi+nginx+mysql 等數據庫)
1-首先說一下如果不用nginx如何在服務器上部署服務
我們都知道django自帶測試服務器,但是該服務器只限於開發使用,那麼我們真正部署時要使用gunicorn或者wsgi代替本身自帶的測試服務器:使用任何一個都少不了配置,以gunicorn的配置文件來說明:
1.1-在django服務的manage.py的同級目錄下創建文件gunicorn.con(文件名自定義)
1.2-下面是幾個簡單的配置說明:
# gunicorn所在位置(可使用命令-- whereis gunicorn 查看)
command = '/root/.virtualenvs/gwcomments/bin/gunicorn'
# 項目所在目錄,manage.py所在目錄,找到manage.py,使用命令 pwd 查看
pythonpath = '/data/gwcomments/gwcomments'
# 運行服務的ip和端口
bind = '127.0.0.1:8000'
# 線程數 cpu數*2 + 1
workers = 2
# 日誌存放目錄以及格式
accesslog = '/var/gwcomments/accesslog.txt'
access_log_format = '%(h)s %(a)s %(l)s %(u)s %(s)s %(D)s %(r)s %(t)s'
errorlog = '/var/gwcomments/errorlog.txt'
loglevel = 'info'
現在啓動服務就不再使用python manage.py runserver了,而是使用gunicorn來啓動服務: gunicorn gwcomments.wsgi -c gunicorn.con
然後使用你服務器的ip:啓動端口/url來看是否可以成功訪問(49.***.***.***:8000/test_url)
2-使用nginx只配置反向代理
上面的步驟依然是必須的,只有啓動基本服務,我們纔可以通過使用nginx來做反向代理,只需要在ngixn上做簡單的配置即可
server {
listen 8082; # 監聽的端口號
server_name loaclhost; # 域名/ip
location / { # 路徑
proxy_pass http://127.0.0.1:8000; # gunicorn中服務啓動的ip和端口號
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
現在因爲做了反向代理,訪問的時候要使用nginx監聽的端口和ip了(49.***.***.***:8082/test_url)
3-使用nginx只配置負載均衡
upstream gwcomments { # gwcomments這個名字是隨意起的
server 127.0.0.1:8000 weight=1 max_fails=2 fail_timeout=30s; # 你自己啓動的服務1
server 127.0.0.1:8001 weight=1 max_fails=2 fail_timeout=30s; # 你自己啓動的服務2
}
server {
listen 8083;
server_name loaclhost;
location / {
proxy_pass http://gwcomments; # //後面不再是ip了,而是upstream後自定義名稱
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
現在不僅做了反向代理,而且還有負載均衡,訪問的時候要還是使用nginx監聽的端口和ip了(49.***.***.***:8083/test_url)