前端全栈之路——nginx(动静分离、负载均衡)

608 阅读6分钟

购买服务器

  • 如果是学生党或者家里有学生的,可以去阿里云申请一个免费的云服务器 developer.aliyun.com/adc/student…
  • 如果不是上面的情况可以自己买一个服务器练习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处理不用后台服务处理静态资源,访问更快捷。

  • 安装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.启动服务

// 后面带&为了进行进程守护
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

  2. 输入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的概率会更多一些,因为权重比较高

结语

如果喜欢的话,点赞关注吧,后面会有更多内容!