前端全棧之路——nginx(動靜分離、負載均衡)

購買服務器

  • 若是是學生黨或者家裏有學生的,能夠去阿里雲申請一個免費的雲服務器

developer.aliyun.com/adc/student…javascript

  • 若是不是上面的狀況能夠本身買一個服務器練習nginx,選擇按量計費就能夠

鏈接遠程服務器

ssh root@xxxx.xx.xx.xx(IP)
複製代碼

安裝nginx

  • 安裝nginx
yum -y install gcc make zlib-devel pcre pcre-devel openssl-devel
sudo yum install -y nginx
複製代碼
  • 啓用並啓動nginx服務:
sudo systemctl enable nginx
sudo systemctl start nginx
複製代碼
  • 配置防火牆80與443
systemctl start firewalld.service //啓動防火牆
sudo firewall-cmd --permanent --zone=public --add-service=http 
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --reload
複製代碼
  • 查看nginx是否正常工做
// 打開瀏覽器而且輸入服務網的公網IP,看是否會出現nginx默認的頁面
// 這裏可能會碰到一個問題就是網站一直在加載沒有任何響應
// 這種狀況,阿里雲鬚要在服務器實例裏面修改安全組配置,新增長一個80端口
// https://blog.csdn.net/qq_43671933/article/details/103865634
複製代碼

nginx經常使用命令

  • 查看nginx狀態
sudo systemctl status nginx
複製代碼
  • 啓用nginx服務器
sudo systemctl start nginx
複製代碼
  • 從新加載nginx服務器
sudo systemctl reload nginx
複製代碼
  • 禁用nginx服務器
sudo systemctl disable nginx
複製代碼

查看配置

  • 查看nginx相關目錄
rpm -ql nginx

/etc/logrotate.d/nginx
/etc/nginx/fastcgi.conf
/etc/nginx/fastcgi.conf.default
/etc/nginx/fastcgi_params
/etc/nginx/fastcgi_params.default
/etc/nginx/koi-utf
/etc/nginx/koi-win
/etc/nginx/mime.types
/etc/nginx/mime.types.default
/etc/nginx/nginx.conf
/etc/nginx/nginx.conf.default
/etc/nginx/scgi_params
/etc/nginx/scgi_params.default
/etc/nginx/uwsgi_params
/etc/nginx/uwsgi_params.default
/etc/nginx/win-utf
/usr/bin/nginx-upgrade
/usr/lib/.build-id
/usr/lib/.build-id/2d
/usr/lib/.build-id/2d/da6018ae12edb856ad3d2cf61bf586b6b4873c
/usr/lib/systemd/system/nginx.service
/usr/lib64/nginx/modules
/usr/sbin/nginx
/usr/share/doc/nginx
/usr/share/doc/nginx/CHANGES
/usr/share/doc/nginx/README
/usr/share/doc/nginx/README.dynamic
/usr/share/licenses/nginx
/usr/share/licenses/nginx/LICENSE
/usr/share/man/man3/nginx.3pm.gz
/usr/share/man/man8/nginx-upgrade.8.gz
/usr/share/man/man8/nginx.8.gz
/usr/share/nginx/html/404.html
/usr/share/nginx/html/50x.html
/usr/share/nginx/html/index.html
/usr/share/nginx/html/nginx-logo.png
/usr/share/nginx/html/poweredby.png
/usr/share/vim/vimfiles/ftdetect/nginx.vim
/usr/share/vim/vimfiles/indent/nginx.vim
/usr/share/vim/vimfiles/syntax/nginx.vim
/var/lib/nginx
/var/lib/nginx/tmp
/var/log/nginx
複製代碼
  • 打開nginx配置文件
cd /etc/nginx
ls -a

.             fastcgi.conf.default    mime.types          scgi_params.default
..            fastcgi_params          mime.types.default  uwsgi_params
conf.d        fastcgi_params.default  nginx.conf          uwsgi_params.default
default.d     koi-utf                 nginx.conf.default  win-utf
fastcgi.conf  koi-win                 scgi_params
複製代碼
  • 分析配置
/etc/nginx/nginx.conf.default

# 工做進程會根據服務器cup核數設置
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request"'
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        error_page  404              /404.html;
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
}

複製代碼
/etc/nginx/nginx.conf

user nginx;
# 工做進程數量
worker_processes auto;

# 錯誤日誌輸出文件
error_log /var/log/nginx/error.log;

# nginx進程
pid /run/nginx.pid;

include /usr/share/nginx/modules/*.conf;

events {
    # nginx服務鏈接數量
    worker_connections 1024;
}

# http服務全局配置
http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    #日誌文件
    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    
    #此選項容許或禁止使用socke的TCP_CORK的選項,此選項僅在使用sendfile的時候使用
    tcp_nopush          on;
    tcp_nodelay         on;
    
    #keepalive超時時間。
    keepalive_timeout   65;
    types_hash_max_size 2048;
	
    # 引入MIME-Type
    include             /etc/nginx/mime.types;	
    default_type        application/octet-stream;

    # 加載/etc/nginx/conf.d下因此的server配置
    include /etc/nginx/conf.d/*.conf;
    
    # 對應端口的服務,能夠存在多個
    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        
        # 服務根目錄
        root         /usr/share/nginx/html;

        # 引入 /etc/nginx/default.d下的全部location路由配置
        include /etc/nginx/default.d/*.conf;
        
        location / {}
        
        #404頁面
        error_page 404 /404.html;
            location = /40x.html {
        }
        
        #50x頁面
        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }
}
複製代碼

修改配置

  • 新建一個index.html
cd /
mkdir data && cd data
mkdir www 
vim index.html //隨便寫一點html保存
複製代碼
  • 修改入口文件
/etc/nginx/nginx.conf

# nginx默認80端口的根目錄/usr/share/nginx/html
# 因此須要修改server下的root
server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root         /data/www;	//修改這個配置
        
        ...
}
複製代碼
  • 添加路由
/etc/nginx/nginx.conf

server {
        ...
        
        // 爲了儘量的不修改默認的nginx配置
        // 咱們在 /etc/nginx/default.d下新建default.conf文件添加路由
        include /etc/nginx/default.d/*.conf;
        
        // 將這行刪除,若是不刪除,輸入IP會顯示nginx默認的頁面
        // 並且上面的配置若是有重複的location / {...}會報錯
        location / {}
        
       	...
}
複製代碼
/etc/nginx/default.d/default.conf

// ~表明後面的是正則表達	.*/.(html|js|css)$ => /.*/.(html|js|css)$/
location ~ .*/.(html|js|css)$ {
	root	/	data/www;
}
複製代碼
  • 檢查更新nginx配置
nginx -t	//檢查nginx配置是否正確
nginx -s reload	//從新加載nginx配置
複製代碼
  • 查看效果
// 打開瀏覽器而且輸入服務網的xxxx.xx.x.xx(IP)/index.html
複製代碼

設置緩存和開啓壓縮

/etc/nginx/default.d/default.conf

location ~ .*/.(html|js|css)$ {
	
    # 設置緩存時間
    expires 1h;
    
    # 開啓gzip壓縮
    gzip	on;
    
    # gzip壓縮版本 
    gzip_http_verson	1.1;
    
    # gzip壓縮等級
    gzip_comp_level	2;
    
    # gzip支持壓縮js和css
    gzip_types	application/javascript	text/css;
    root	/data/www;
}
複製代碼

防盜鏈

/etc/nginx/default.d/default.conf

location ~ .*/\.(jpg|png)$ {
    # 圖片防盜鏈
    valid_referers	none blocked http://xxxx.xx.x.xx(容許訪問的IP)
    if ($invalid_referer) {
    	return 403;
    }
    # 圖片目錄
	root	/data/images;
}
複製代碼

設置CORS

/etc/nginx/default.d/default.conf

location ~ .*/\.json$ {
    # 容許任何其餘網站跨域訪問
    add_header	Access-Control-Allow-Origin *;
    
    # 容許跨域訪問的請求類型 
    add_header	Access-Control-Allow-Methods GET,POST,DELETE;
    add_header	Access-Control-Allow-Headers Content-Type;
    root    /data/json;
}
複製代碼

反向代理實現動靜分離

動靜分離是將網站靜態資源(HTML,JavaScript,CSS,img等文件)與後臺應用分開部署,提升用戶訪問靜態代碼的速度,下降對後臺應用訪問。通常都是將靜態資源放置在一臺或多臺服務器上面,後臺服務放置在一臺服務器上面分開。這裏使用nginx在一臺服務器上實現動靜分離,靜態資源直接nginx處理不用後臺服務處理靜態資源,訪問更快捷。css

  • 安裝node環境
  1. 查看centos8存儲庫node版本列表
yum module list nodejs

CentOS-8 - AppStream
Name     Stream   Profiles                                   Summary            
nodejs   10 [d]   common [d], development, minimal, s2i      Javascript runtime 
nodejs   12       common [d], development, minimal, s2i      Javascript runtime 
nodejs   14 [e]   common [d] [i], development, minimal, s2i  Javascript runtime 
複製代碼
  1. 安裝node14.x
sudo yum module install nodejs:14
複製代碼
  1. 查看安裝結果
node -v
npm -v
複製代碼
  • 建立node服務
  1. 在/home下建立3000.js
/home/3000.js

let http = require('http');
http.createServer(function(req,res){
	res.end('node server 3000');
}).listen(3000)
複製代碼
  1. 在/home下建立4000.js
/home/4000.js

let http = require('http');
http.createServer(function(req,res){
	res.end('node server 4000');
}).listen(4000)
複製代碼

3.啓動服務html

// 後面帶&爲了進行進程守護
node 3000.js &
node 4000.js &
複製代碼
  • 修改電腦host配置文件
sudo vim /etc/hosts

// 將這段話加加到最後面
xxxx.xx.xxx.xx(你的遠程服務器IP)   www.test1.cn
xxxx.xx.xxx.xx(你的遠程服務器IP)   www.test2.cn
複製代碼
  • 修改nginx配置
/etc/nginx/nginx.conf

// 設置2個反向代理,經過將請求代理給相應的node服務
// 靜態資源會訪問/data/www目錄下的文件
// 動態渲染的頁面等會交給相應的後臺服務處理
...
server {
	listen		80;
    server_name	localhost;
   	root	/data/www;
}
server {
	listen		80;
    server_name	www.test1.cn;
    location / {
    	proxy_pass	http://localhost:3000;
    }
}
server {
	listen		80;
    server_name	www.test2.cn;
    location / {
    	proxy_pass	http://localhost:4000;
    }
}
...
複製代碼
  • 從新加載配置
nginx -t
nginx -s reload
複製代碼
  • 瀏覽器查看
  1. 輸入www.test1.cn

  1. 輸入www.test2.cn

負載均衡

  • 修改電腦host配置文件
sudo vim /etc/hosts

// 將這段話加加到最後面
xxxx.xx.xxx.xx(你的遠程服務器IP)   www.test.cn
xxxx.xx.xxx.xx(你的遠程服務器IP)   www.test1.cn
xxxx.xx.xxx.xx(你的遠程服務器IP)   www.test2.cn
複製代碼
  • 修改nginx配置
/etc/nginx/nginx.conf
...

// 設置2個反向代理,經過將請求代理給相應的node服務
// 設置一個反向代理,這個反向代理不須要有對應的後臺服務
// 而後設置upstream將請求根據權重分發給另外兩個服務 
upstream test {
  // weight權重 
  server localhost:3000 weight=2; 
  server localhost:4000 weight=1;
}
server {
  listen 80;
  server_name	localhost;
}
server {
  listen 80;
  server_name	www.test.cn;
  location / {
  	// 名稱和上面對應就行
    proxy_pass	http://test;
  }
}
server {
  listen 80;
  server_name	www.test1.cn;
  location / {
    proxy_pass	http://localhost:3000;
  }
}
server {
  listen 80;
  server_name     www.test2.cn;
  location / {
    proxy_pass    http://localhost:4000;
  }
}
    
...
複製代碼
  • 從新加載配置
nginx -t
nginx -s reload
複製代碼
  • 瀏覽器查看

輸入www.test.cn,會看到返回的結果在洗面兩種狀況中隨機出現,而且3000的機率會更多一些,由於權重比較高 java

結語

若是喜歡的話,點贊關注吧,後面會有更多內容!node

相關文章
相關標籤/搜索