[原創]Nginx反向代理及負載均衡

candy-yun發表於2017-06-11

1、基本命令

# 啟動nginx
start nginx.exe # windows
nginx -c /usr/local/nginx/conf/nginx.conf # Linux
# 優雅的停止nginx nginx
-s stop # 立即停止nginx nginx -s quit # 重新開啟日誌檔案 nginx -s reopen # 平滑的重啟nginx並重新載入nginx的配置檔案 nginx -s reload
# 可以用來修改配置檔案之後,測試配置檔案是否有語法錯誤 nginx
-t

2、通過訊號量來控制nginx

其實質是通過訊號量來對nginx進行控制的,所以也可以通過下面的方式來控制nginx:

kill -INT `cat /usr/local/nginx/logs/nginx.pid`
[root@localhost logs]# kill -INT `cat /usr/local/nginx/logs/nginx.pid`
[root@localhost logs]# ps -elf|grep nginx
0 S root      3843  1306  0  80   0 -  1088 -      16:37 pts/1    00:00:00 grep nginx

 看到nginx的兩個程式被我們殺掉了。還有其他的訊號量可以使用,分別對應到上面的命令。

kill -HUP pid,  kill -USR1 pid, kill -USR2 pid 等等,總結如下:

1. TERM,INT : Quick shutdown,立即關閉程式,不管他有沒有在處理請求;

2. QUIT : Graceful shutdown, 優雅的關閉程式,也就是等到該程式處理的請求都完成之後才關閉;

3. HUP : Configuration reload, start the new worker processes with a new configuration. Gracefully shutdown the old worker processes

4. USR1 : Reopen the log files, 重新開啟日誌檔案,在備份日誌按月/日分割日誌時用;

5. USR2 : Upgrade Executable on the fly, 平滑的升級;

6. WINCH : Gracefully shutdown the worker processes, 優雅的關閉舊的程式(配合USR2來進行升級);

3、圖片請求重寫到其他伺服器

前臺伺服器對外使用,其中的圖片是由後臺管理伺服器管理的。同時圖片的處理模式是DB儲存後臺管理伺服器的訪問路徑,檔案以流的方式儲存在後臺管理伺服器的某一路徑。

在投產使用時,由於公網IP和域名不充足的原因,決定只將前臺伺服器與域名繫結,後臺管理伺服器使用IP+埠/域名+埠的形式訪問。

為了避免IP和埠及應用名暴露出來,現在使用nginx進行反向代理。

 Nginx配置:

# 將http://pic.candy.com/pic請求重寫到http://localhost:8080/back/pic

worker_processes  1;
events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    
    log_format  main  `$remote_addr - $remote_user [$time_local] "$request" ` `$status $body_bytes_sent "$http_referer" ` `"$http_user_agent" "$http_x_forwarded_for"`;
    
    
    server
	  {
				listen       80;
				server_name pic.candy.com;
				
				
    		access_log  logs/access.log  main;
    
			  # 將http://pic.candy.com/pic請求重寫到http://localhost:8080/back/pic
				location ~ ^/pic/(.*).(png|jpg|gif)$
				{
				   rewrite ^/pic/(.*).(png|jpg|gif)$ http://localhost:8080/back/pic/$1.$2 break;
				}
  	}
}

 

作者: Candyメ奶糖

本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段宣告,且在文章頁面明顯位置給出原文連線,否則保留追究法律責任的權利。
博文來源廣泛,如原作者認為我侵犯智慧財產權,請儘快給我發郵件
359031282@qq.com聯絡,我將以第一時間刪除相關內容。


相關文章