nginx初學指南

nginx 概述:

nginx 服務由一個 master 進程和多個 worker 進程組成,master 進程主要負責讀取和應用配置,以及維護 worker 進程,worker 進程負責實際處理請求。Nginx 基於事件處理機制來高效地將請求分配給 worker 進程,worker 進程的數量可以在配置文件中預先定義好或者基於可用CPU數量自動調整匹配。

 

nginx 配置文件:

  1. 配置文件默認路徑爲 /usr/local/nginx/conf/nginx.conf,或者 /etc/nginx/nginx.conf,或者 /usr/local/etc/nginx/nginx.conf
  2. 配置文件由指令和指令塊(block)組成,單個指令有指令名和參數組成,英文分號(;)結尾。指令塊由大括號({})將多個指令包括起來,如果一個指令塊中可以包含其他指令塊,則稱這個指令塊爲一個上下文(context),例如 eventshttpserverlocation 等。

如果指令沒有被包括任何上下文中,則認爲其在上下文 main 中。events http 的指令被放在上下文 main 中,server 的指令在上下文 http 中,location 的指令在 server 中。

配置文件中通過 # 來定義註釋。

 

nginx 進程啓動後,可以通過nginx -s <signal> 參數向 master 進程發送信號,信號有下面幾種:

  1. stop:快速停止 nginx 進程。
  2. quit:同樣是停止進程,但是會等待全部 worker 進程處理完成當前已經收到的請求。
  3. reload:當 master 進程收到 reload 信號後,會首先檢查新的配置文件的語法,如果檢查通過,master 進程會啓動新的 worker 進程,併發消息給舊的 worker 進程通知其關閉,當 worker 進程收到關閉通知後,會停止接收新的請求,處理完成當前處理中的請求,然後退出。如果配置文件檢查沒有通過,master 進程會回滾配置並仍然使用原有配置工作。
  4. reopen:重新打開(新的)日誌文件,該操作可以用於日誌的分割,例如當日志積累到一定大小後,先使用 mv 命令將原日誌移動到新的目錄下,然後使用 reopen 信號告知 nginx 重新打開新的日誌文件用於日誌記錄。

 

nginx 反向代理和負載均衡的基礎配置實驗:

nginx服務器我們安裝在一臺CentOS 7.3上面,後端兩臺server一臺是CentOS 6.9搭建的Apache,一臺用Windows Server 2012搭建的IIS

 

CentOS6.9搭建Apache

安裝:yum installhttpd

啓動服務:servicehttpd start

配置開機啓動:chkconfighttpd on

找一個測試用的http模板網站上傳到httpd默認目錄/var/www/html下(在/etc/httpd/conf/httpd.conf中配置),如果需要的話,調整一下iptables。測試站點是否可以訪問:

C 0 0 139.219.111.108/index.html BRILLIANT Dashboard UI Elements Charts Tabs & Panels Responsive Tables Forms Multi-Level Dropdown Empty Page Dashboard Welcome John Doe Home Dashboard / Data 44,023 DAILY VISITS Line Chart Profit 32,850 SALES Sales 56,150 COMMENTS Bar Chart Customers 89,645 DAILY PROFITS No. of Visits

 

Windows Server 2012搭建IIS站點:

安裝:在添加刪除角色和功能(Rolesand Features)中添加Web Server (IIS)

Select server roles Before You Begin Installation Type Server Selection Server Role: Features Web Server Role (IIS) Role Services Confirmation d Roles and Features Wizar Select one or more roles to install on the selected server. Roles Active Directory Rights Management Services Application Server DHCP Server DNS Server Fax Server File And Storage Services (Installed) Hyper v Network Policy and Access Services Print and Document Services Remote Access Remote Desktop Services Volume Activation Services eb Server (IIS] Windows Deploymnent Services Windows Server Update Services DESTINATION SERVER Description Web Server (IIS) prcNides a reliable, manageable, and scalable Web application infrastructure. Cancel

默認安裝後,找一個測試用的http模板網站上傳到http默認目錄C:\inetpub\wwwroot下,如果需要的話,調整一下防火牆規則。測試站點是否可以訪問:

0 139.219.65.87 MARBLE HOME BLOG PORTFOLIO ABOUT CONTACT 2016 Blend Free HTMLS All Rights Reserveff More Templates - Collect from ive is How Give We the User New Superpowers plates LIVE PREVIEW - Collect from LEARN MORE*

 

安全起見我們可以把後端這兩臺serverhttp偵聽端口修改爲一個高位端口,例如:61234

CentOS 6.5上面修改/etc/httpd/conf/httpd.conf中的Listen端口,Windows IIS上面修改bind中的綁定端口。

 

配置好之後,開始搭建nginx

首先添加nginxrepo,添加/etc/yum.repos.d/nginx.repo文件,寫入下面的內容:

[nginx]

name=nginxrepo

baseurl=http://nginx.org/packages/centos/$releasever/$basearch/

gpgcheck=0

enabled=1

保存退出,使用yuminstall nginx安裝。

安裝完成後啓動服務:systemctlstart nginx

設置開機啓動:systemctlenable nginx

測試nginx安裝是否成功:

0 139.219.7048 Welcome to nginx! If you see this page, the nginx web server is successfully installed and working. Further configuration is required. For online documentation and support please refer to ngjnx:ocg. Commercial support is available at nginx.com. Thank you for using nginx.

 

接下來就是配置nginx配置文件了,由於nginx模塊非常多,所以可以變查變學習nginx各個模塊對應的配置,可以參考官網上面的說明:

http://nginx.org/en/docs/

舉個例子,要配置http的配置,就可以在上面鏈接中找到ngx_http_core_module模塊,打開對應的鏈接,裏面會有http配置的詳細指令和參數說明,如果要了解http下面的upstream模塊,可以找到ngx_http_upstream_module的鏈接查看。

 

接着我們配置一個簡單的負載均衡,修改/etc/nginx/nginx.conf文件內容如下:

user  nginx;

worker_processes  1;

 

error_log  /var/log/nginx/error.log warn;

pid        /var/run/nginx.pid;

 

 

events {

    worker_connections  1024;

}

 

http{

    include /etc/nginx/mime.types;

    default_type application/octet-stream;

 

    upstream backend{

        server 172.16.0.11:61234;

        server 172.16.0.6:61234;

    }

 

    server{

        listen 80;

        server_name localhost;

        location / {

            proxy_pass http://backend;

        }

    }

}

上面配置裏面172.16.0.11172.16.0.6分別是前面我們做的IISApache的機器的內網地址,配置完成後使用nginx -s reload

 

嘗試訪問一下nginx,發現提示502 Bad Gateway

C O G) 139.219.66.126 502 Bad Gateway nginxfl.12_l

 

首先使用paping測試一下nginx到兩臺後端web服務器是否可達:

[root@DanCentOS73 ./paping -c 4 172.16.€.6 paping v1.5.5 - Copyright (c) 2611 Mike Lovell -p 61234 Connecting to 172.16.e.6 Connected to 172.16.e.6: Connected to 172.16.e.6: Connected to 172.16.e.6: Connected to 172.16.e.6: Connection statistics: on TCP 61234: t im e=e. 87ms t im e=e. ggms t im e=B. 86ms t ime=e. glms p rotocol= protocol= protocol= p rotocol= Failed TCP port-61234 TCP port-61234 TCP port-61234 TCP port-61234 e (8.88%) Attanpted = 4, Connected = 4, Approximate connection times: Minimum = 8.86ms, [root@DanCentOS73 paping v1.5.5 - Copyright connecting to 172.16.e.11 Connected to 172.16.8.11: Connected to 172.16.8.11: Connected to 172.16.8.11: Connected to 172.16.8.11: Connection statistics: Maximum = e.ggms, Average e. glms ./paping -c 4 172.16. (c) 2611 Mike Lovell on TCP 61234: t im e=1.8gms t im e=l. g2ms t im e=l. BBms t ime=e. 7gms 4, p rotocol= protocol= protocol= p rotocol= Failed €.11 -p 61234 TCP port-61234 TCP port-61234 TCP port-61234 TCP port-61234 e (8.88%) Attanpted = 4, Connected Approximate connection times: Minimum = B.7gms, Maximum 1.g2ms, Average = 1.4Bms

 

再測試一下web頁面是否能夠返回內容:

[root@Dancent0S73 curl http://172.16.€.6:61234 *DOCTYPE html>  Free Bootstrap Admin c! Bootstrap Styles--> clink .css" /> - FontAwesome Styles--> clink /> c! Morris Chart Styles--> clink c! Custom Styles--> clink -styles.css" /> c! Google Fonts--> clink href= •https://fonts.googleapis.com/css?family=Open+Sans• clink -Chart/cssCharts .css type= •text/css ' <bodp <div •wrapper <nav navbar-default top -navbar" <div role= "navigation

 

測試發現都沒問題並且nginx的配置也正常,再查看一下nginxerrorlog

[root@DanCentOS73 tail -n 26 /var/log/nginx/error.log 2€17/1€/24 [crit] 3781#3781: *139 connect() to 172.16.€.6:61234 failed (13: Pemission denied) while connecting to upstream, client: 1@6.12€.78.19€, server: localhost, request: "GET / HTTP/I.I", upstream: "htt host: "139.219.66.126" 2€17/1€/24 €7:52 [warn] 3781#3781: *139 upstream server tanporarily disabled while connecting to upstream, client: 1@6.12€.78.19€, server: localhost, request: "GET / HTTP/1.r•, upstream: 'http://172.16.€.6:61234/", host: "139.219.66.126" 2€17/1€/24 [crit] 3781#3781: *139 connect() to 172.16.€.11:61234 failed (13: Pemission denied) whil e connecting to upstream, client: 1@6.12€.78.19€, server: localhost, request: "GET / HTTP/I.I", upstream: •ht host: "139.219.66.126" 2€17/1€/24 [warn] 3781#3781: *139 upstream client: 1@6.12€.78.19€, server: localhost, request: host: "139.219.66.126" 2€17/1€/24 [error] 3781#3781: *139 no live 8.196, server: localhost, request: "GET / HTTP/I.I", 2€17/1€/24 [error] 3781#3781: *139 no live 8.196, server: localhost, request: "GET / HTTP/I.I", 2€17/1€/24 [error] 3781#3781: *139 no live localhost, request: "GET / HTTP/I.I", 8.196, server: server tanporarily disabled while connecting to upstream, "GET / HTTP/1.r•, upstream: upst reams upst ream : upst reams upst ream : upstreams upst ream : while connecting to "http://backend/ • , while connecting to "http://backend/ • , while connecting to "http://backend/", 'http://172.16.€.11:61234/", upstream, client: 1@6.12€.7 host: "139.219.66.126" upstream, client: 1@6.12€.7 host: "139.219.66.126" upstream, client: 1@6.12€.7 host: "139.219.66.126"

 

可以看到在連接後端兩臺web服務器的時候報Permission denied,於是使用setenforce0selinux關閉,再次訪問發現正常了:

C 0 0 139.219.66.126 MARBLE HOME BLOG PORTFOLIO ABOUT CONTACT 2016 Blend Free HTMLS All Rights Reserved We are Happy to Create Newest Modern Websites LIVE PREVIEW LEARN MORE*

多測試幾次看一下負載均衡是否運行正常:

C 0 0 139 219.66.126 BRILLIANT Dashboard UI Elements Charts Tabs & Panels Responsive Tables Forms Multi-Level Dropdown Empty Page Dashboard Welcome John Doe Home Dashboard / Data 44,023 DAILY VISITS Line Chart Profit Line Chart 200 32,850 SALES Sales 56,150 COMMENTS Bar Chart Customers Bar Chart Example 89,645 DAILY PROFITS No. of Visits 46%

 

測試沒問題,最後把selinux配置文件修改下,大功告成:

[root@DanCentOS73 nginx]# vim /etc/selinux/config # This file controls the state of SELinux on the systan. # SELIWX= can take one of these three values: enforcing - SELinux security policy is enforced. permissive - SELinux prints warnings instead of enforcing. disabled - No SELinux policy is loaded. SELIwx=disab1ed # SELIWXTYPE= can take one of three two values: targeted - Targeted processes are protected, minimum - Modification of targeted policy. Only selected processes are protected. mls - Multi Level Security protection. SELIWXTYPE=ta rgeted

 

當然,nginx能夠實現的功能以及後續的優化還有很多,具體就需要各位看官實踐出真知了~~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章