您的位置:首页 > 运维架构 > 反向代理

Nginx服务器搭建, 反向代理, 负载均衡, 状态监控

2018-01-25 15:08 681 查看

nginx服务器搭建

nginx服务器搭建

nginx简介

下载安装包和模块库

安装模块库和Nginx
1安装pcre

2安装nginx

Nginx配置

开启外网访问

正向代理和反向代理
1正向代理的概念

2反向代理的概念

3两者区别

Nginx反向代理配置

Nginx负载均衡配置
upstream支持的负载均衡算法
1轮询默认

1weight

2ip_hash

3fair三方

4url_hash第三方

upstream 支持的状态参数

负载均衡之多个服务器配置

Nginx服务状态监控

1.nginx简介

Nginx (“engine x”) 是一个高性能的 HTTP 和 反向代理 服务器,也是一个 IMAP/POP3/SMTP 代理服务器,在高连接并发的情况下Nginx 是 Apache 服务器不错的替代品.其特点是占有内存少,并发能力强,事实上nginx的并发能力确实在同类型的网页服务器中表现较好.目前中国大陆使用nginx网站用户有:新浪、网易、 腾讯,另外知名的微网志Plurk也使用nginx。

Nginx 作为 负载均衡 服务器:

Nginx 既可以在内部直接支持 Rails 和 PHP 程序对外进行服务,也可以支持作为 HTTP 代理服务器对外进行服务。 Nginx 采用 C 进行编写, 不论是系统资源开销还是 CPU 使用效率都比 Perlbal 要好很多。作为邮件代理服务器:

Nginx 同时也是一个非常优秀的邮件代理服务器(最早开发这个产品的目的之一也是作为邮件代理服务器), Last.fm 描述了成功并且美妙的使用经验。Nginx 是一个安装非常简单,配置文件非常简洁(还能够支持perl语法), Bugs非常少的服务器: Nginx 启动特别容易,并且几乎可以做到 7*24 不间断运行,即使运行数个月也不需要重新启动。 你还能够不间断服务的情况下进行软件版本的升级。

2.下载安装包和模块库

1)下载openssl-fips-2.0.16.tar.gz 下载地址为https://www.openssl.org/source/ openssl库

2)下载zlib-1.2.11.tar.gz 下载地址为http://www.zlib.net/, gzip 模块

3) 下载pcre-8.41.tar.gz 下载地址为https://ftp.pcre.org/pub/pcre/, 该文件为正则表达式库。让nginx支持rewrite需要安装这个库。

4)下载nginx-1.13.8.tar.gz 下载地址为http://nginx.org/download/nginx-1.13.8.tar.gz, 该文件为nginx的linux版本安装文件。

模块依赖性Nginx需要依赖上边三个包 , 依赖包安装顺序依次为:openssl、zlib、pcre, 然后安装Nginx包.

3.安装模块库和Nginx

安装包和模块库全部放在目录 /usr/local/ 下



1)安装pcre

解压安装包: tar zxvf pcre-8.41.tar.gz

进入安装包目录: cd pcre-8.41

编译安装 : ./configure

​ make && make install

查看pcre版本: pcre-config –version

如下,表示pcre安装成功



2)安装nginx

解压安装包: tar zxvf nginx-1.13.8.tar.gz

进入安装包目录: cd nginx-1.13.8

编译安装:

./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-pcre=/usr/local/pcre-8.41


./configure之后的结果为:

Configuration summary
+ using PCRE library: /usr/local/pcre-8.41
+ using system OpenSSL library
+ using system zlib library

nginx path prefix: "/usr/local/nginx"
nginx binary file: "/usr/local/nginx/sbin/nginx"
nginx modules path: "/usr/local/nginx/modules"
nginx configuration prefix: "/usr/local/nginx/conf"
nginx configuration file: "/usr/local/nginx/conf/nginx.conf"
nginx pid file: "/usr/local/nginx/logs/nginx.pid"
nginx error log file: "/usr/local/nginx/logs/error.log"
nginx http access log file: "/usr/local/nginx/logs/access.log"
nginx http client request body temporary files: "client_body_temp"
nginx http proxy temporary files: "proxy_temp"
nginx http fastcgi temporary files: "fastcgi_temp"
nginx http uwsgi temporary files: "uwsgi_temp"
nginx http scgi temporary files: "scgi_temp


然后 make 然后make install

查看nginx版本: /usr/local/nginx/sbin/nginx -v

结果如下,则表示安装成功:



到此,nginx安装完成。

4.Nginx配置

进入到nginx安装目录, 启动nginx服务, 无法开启, 提示错误如下 :80端口被占用。

[root@iZwz98b01mzud1ytnw5g22Z nginx-1.13.8]# cd ..
[root@iZwz98b01mzud1ytnw5g22Z local]# cd nginx
[root@iZwz98b01mzud1ytnw5g22Z nginx]# /usr/local/nginx/sbin/nginx
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] still could not bind()
[root@iZwz98b01mzud1ytnw5g22Z nginx]#


查看nginx的配置文件, nginx服务器使用的是80端口:

nginx.conf文件的具体配置参考网址: http://blog.csdn.net/tjcyjd/article/details/50695922

[root@iZwz98b01mzud1ytnw5g22Z nginx]# ls
client_body_temp  conf  fastcgi_temp  html  logs  proxy_temp  sbin  scgi_temp  uwsgi_temp
[root@iZwz98b01mzud1ytnw5g22Z nginx]# cat conf/nginx.conf

#user  nobody;          #nginx运行使用的用户
worker_processes  1;    #工作进程:数目。根据硬件调整,通常等于CPU数量或者2倍于CPU。

#日志位置和日志级别
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

# 没个工作进程的最大连接数量。根据硬件调整,和前面工作进程配合起来用,尽量大,但是别把cpu跑到100%就行。##每个进程允许的最多连接数,理论上每台nginx服务器的最大连接数为。
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; #keepalive超时时间。

#gzip  on;

#下面是server虚拟主机的配置
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;

# redirect server error pages to the static page /50x.html
#
error_page   500 502 503 504  /50x.html;
location = /50x.html {
root   html;
}

# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
#    proxy_pass   http://127.0.0.1; #}

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
#    root           html;
#    fastcgi_pass   127.0.0.1:9000;
#    fastcgi_index  index.php;
#    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
#    include        fastcgi_params;
#}

# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
#    deny  all;
#}
}

# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
#    listen       8000;
#    listen       somename:8080;
#    server_name  somename  alias  another.alias;

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

# HTTPS server
#
#server {
#    listen       443 ssl;
#    server_name  localhost;

#    ssl_certificate      cert.pem;
#    ssl_certificate_key  cert.key;

#    ssl_session_cache    shared:SSL:1m;
#    ssl_session_timeout  5m;

#    ssl_ciphers  HIGH:!aNULL:!MD5;
#    ssl_prefer_server_ciphers  on;

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

}
[root@iZwz98b01mzud1ytnw5g22Z nginx]#


编辑配置文件, 将端口号改为81, 修改serverName, vim conf/nginx.conf



然后重启nginx服务, 如下表示nginx服务成功启动

[root@iZwz98b01mzud1ytnw5g22Z nginx]# /usr/local/nginx/sbin/nginx

[root@iZwz98b01mzud1ytnw5g22Z nginx]# ps -aux | grep nginx
Warning: bad syntax, perhaps a bogus '-'? See /usr/share/doc/procps-3.2.8/FAQ
root     25912  0.0  0.1  42636  1172 ?        Ss   10:30   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nobody   25913  0.0  0.1  43068  1760 ?        S    10:30   0:00 nginx: worker process
root     25922  0.0  0.0 103324   888 pts/2    S+   10:31   0:00 grep nginx
[root@iZwz98b01mzud1ytnw5g22Z nginx]#


但是在浏览器中访问的时候仍然没有结果



5.开启外网访问

在Linux系统中默认有防火墙Iptables管理者所有的端口,只启用默认远程连接22端口其他都关闭,咱们上面设置的81等等也是关闭的,所以我们需要先把应用的端口开启

方法一: 直接关闭防火墙,这样性能较好,但安全性较差,如果有前置防火墙可以采取这种方式

关闭防火墙
[root@localhost ~]# service iptables stop
关闭开机自启动防火墙
[root@localhost ~]# chkconfig iptables off
[root@localhost ~]# chkconfig --list|grep ipt


方法二将开启的端口加入防火墙白名单中,这种方式较安全但性能也相对较差

编辑防火墙白名单
[root@localhost ~]# vim /etc/sysconfig/iptables
增加下面一行代码
-A INPUT -p tcp -m state -- state NEW -m tcp --dport 80 -j ACCEPT
保存退出,重启防火墙
[root@localhost ~]# service iptables restart


针对此操作, 我们先查看下自己的防火墙是否已关闭, 发现防火墙并没有开启, 但是通过windows浏览器访问仍然没有任何效果

[root@iZwz98b01mzud1ytnw5g22Z nginx]# service iptables status
iptables: Firewall is not running.
[root@iZwz98b01mzud1ytnw5g22Z nginx]# service iptables stop
[root@iZwz98b01mzud1ytnw5g22Z nginx]# service iptables status
iptables: Firewall is not running.
[root@iZwz98b01mzud1ytnw5g22Z nginx]#


那我们就尝试把开启的端口加入防火墙白名单中

vim /etc/sysconfig/iptables

-A RH-Firewall-1-INPUT -p tcp -m state -m tcp --dport 81 --state NEW -j ACCEPT

重启防火墙
[root@iZwz98b01mzud1ytnw5g22Z nginx]# service iptables restart
iptables: Applying firewall rules:                         [  OK  ]
[root@iZwz98b01mzud1ytnw5g22Z nginx]#




Linux配置完毕了,使用另一台电脑而非安装nginx的电脑,我是用的windows系统,配置一下host在“C:\Windows\System32\drivers\etc”下的hosts中配置一下域名重定向

39.108.98.36 nginx.test.com


然后cmd再ping一下这个域名是否正确指向了这个IP上



打开这台Windows系统内的浏览器,输入nginx.test.com会得到以下结果,就说明外网访问成功.



到此Nginx服务器雏形部署完成。

Nignx常用命令:

/usr/local/nginx/sbin/nginx -s reload            # 重新载入配置文件
/usr/local/nginx/sbin/nginx -s reopen            # 重启 Nginx
/usr/local/nginx/sbin/nginx -s stop              # 停止 Nginx
/usr/local/nginx/sbin/nginx                      # 启动 Nginx


6.正向代理和反向代理

(1)正向代理的概念

​ 正向代理,也就是传说中的代理,他的工作原理就像一个跳板,简单的说,我是一个用户,我访问不了某网站,但是我能访问一个代理服务器,这个代理服务器呢,他能访问那个我不能访问的网站,于是我先连上代理服务器,告诉他我需要那个无法访问网站的内容,代理服务器去取回来,然后返回给我。从网站的角度,只在代理服务器来取内容的时候有一次记录,有时候并不知道是用户的请求,也隐藏了用户的资料,这取决于代理告不告诉网站。

​ 结论就是,正向代理 是一个位于客户端和原始服务器(origin server)之间的服务器,为了从原始服务器取得内容,客户端向代理发送一个请求并指定目标(原始服务器),然后代理向原始服务器转交请求并将获得的内容返回给客户端。客户端必须要进行一些特别的设置才能使用正向代理。



(2)反向代理的概念

​ 例用户访问 http://www.test.com/readme,但www.test.com上并不存在readme页面,他是偷偷从另外一台服务器上取回来,然后作为自己的内容返回用户,但用户并不知情。这里所提到的 www.test.com 这个域名对应的服务器就设置了反向代理功能。

​ 结论就是,反向代理正好相反,对于客户端而言它就像是原始服务器,并且客户端不需要进行任何特别的设置。客户端向反向代理的命名空间(name-space)中的内容发送普通请求,接着反向代理将判断向何处(原始服务器)转交请求,并将获得的内容返回给客户端,就像这些内容原本就是它自己的一样。



(3).两者区别

用途上来讲:

​ 正向代理的典型用途是为在防火墙内的局域网客户端提供访问Internet的途径。正向代理还可以使用缓冲特性减少网络使用率。反向代理的典型用途是将防火墙后面的服务器提供给Internet用户访问。反向代理还可以为后端的多台服务器提供负载平衡,或为后端较慢的服务器提供缓冲服务。另外,反向代理还可以启用高级URL策略和管理技术,从而使处于不同web服务器系统的web页面同时存在于同一个URL空间下。

安全性来讲:

​ 正向代理允许客户端通过它访问任意网站并且隐藏客户端自身,因此你必须采取安全措施以确保仅为经过授权的客户端提供服务。反向代理对外都是透明的,访问者并不知道自己访问的是一个代理。

7.Nginx反向代理配置

​ Nginx作为近年来较火的反向代理服务器,安装在目的主机端,主要用于转发客户机请求,后台有多个http服务器提供服务,nginx的功能就是把请求转发给后面的服务器,决定哪台目标主机来处理当前请求。下面演示如何进行配置使Nginx发挥作用。

1、模拟n个http服务器作为目标主机

用作测试,简单的使用2个tomcat实例模拟两台http服务器,分别将tomcat的端口改为8082和8083

2、配置IP域名

39.108.98.36 8082.test.com

39.108.98.36 8083.test.com

3、配置nginx.conf

upstream tomcateserver1 {
server 39.108.98.36:8082;
}

upstream tomcateserver2 {
server 39.108.98.36:8083;
}

server {
listen  81;
server_name     8082.test.com;

location / {
#设置主机头和客户端真实地址,以便服务器获取客户端真实IP
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

proxy_pass   http://tomcateserver1;  #设置反向代理的地址
index  index.html  index.htm;
}
}

server {
listen       81;
server_name  8083.test.com;

#charset koi8-r;

#access_log  logs/host.access.log  main;

location / {
proxy_pass  http://tomcateserver2; #root   html;
index  index.html index.htm;
}


流程:

浏览器访问域名 8082.test.com , 通过本地host文件域名解析,找到39.108.98.36服务器(安装有nginx) ; nginx反向代理接受客户机请求,找到server_name为8082.test.com的server节点,根据proxy_pass对应的http路径,将请求转发到upstream tomcateserver1上,即端口号为8082的tomcat服务器。



4.效果展示:





8.Nginx负载均衡配置

Nginx集反向代理和负载均衡于一身,在配置文件中修改配就可以实现 vim conf/nginx.conf , 具体文件内容在第四部分中已经介绍过, 每一个server就是一个虚拟主机,我们有一个当作web服务器来使用.

负载均衡功能往往在接收到某个请求后分配到后端的多台服务器上,那我们就需要upstream{}块来配合使用

upstream xxx{};upstream模块是命名一个后端服务器组,组名必须为后端服务器站点域名,内部可以写多台服务器ip和port,还可以设置跳转规则及权重等等
ip_hash;代表使用ip地址方式分配跳转后端服务器,同一ip请求每次都会访问同一台后端服务器
server;代表后端服务器地址

server{};server模块依然是接收外部请求的部分
server_name;代表外网访问域名
location / {};同样代表过滤器,用于制定不同请求的不同操作
proxy_pass;代表后端服务器组名,此组名必须为后端服务器站点域名

server_name和upstream{}的组名可以不一致,server_name是外网访问接收请求的域名,upstream{}的组名是跳转后端服务器时站点访问的域名


upstream bakend {
ip_hash;
server 139.199.148.55:8080;
server 139.199.148.155:8080;
}


upstream支持的负载均衡算法

1)轮询(默认)

每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器down掉,能自动剔除。

2.1)weight

​ 指定轮询几率,weight和访问比率成正比,用于后端服务器性能不均的情况。

​ upstream bakend {

​ server 139.199.148.55:8080 weight=10;

​ server 139.199.148.155:8080 weight=10;

​ }

2.2)ip_hash

​ 每个请求按访问ip的hash结果分配,这样每个访客固定访问一个后端服务器,有效解决了动态网页存在的session共享问题。

​ upstream bakend {

​ ip_hash;

​ server 139.199.148.55:8080;

​ server 139.199.148.155:8080;

​ }

3)fair(三方)

​ 按后端服务器的响应时间来分配请求,响应时间短的优先分配。Nginx本身是不支持fair的,如果需要使用这种调度算法,必须下载Nginx的upstream_fair模块。

​ upstream backend {

​ server server1;

​ server server2;

​ fair;

​ }

4)url_hash(第三方)

按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器,后端服务器为缓存时比较有效。Nginx本身是不支持url_hash的,如果需要使用这种调度算法,必须安装Nginx 的hash软件包。在upstream中加入hash语句,server语句中不能写入weight等其他的参数,hash_method是使用的hash**算法**

upstream backend {

​ server squid1:3128;

​ server squid2:3128;

​ hash $request_uri;

​ hash_method crc32;

​ }

tips:

upstream bakend{#定义负载均衡设备的Ip及设备状态}{

​ ip_hash;

​ server 127.0.0.1:9090 down;

​ server 127.0.0.1:8080 weight=2;

​ server 127.0.0.1:6060;

​ server 127.0.0.1:7070 backup;

​ }

在需要使用负载均衡的server中增加 proxy_pass http://bakend/;

upstream 支持的状态参数:

1.down表示单前的server暂时不参与负载

2.weight为weight越大,负载的权重就越大。

3.max_fails:允许请求失败的次数默认为1.当超过最大次数时,返回proxy_next_upstream模块定义的错误

4.fail_timeout:max_fails次失败后,暂停的时间。

5.backup: 其它所有的非backup机器down或者忙的时候,请求backup机器。所以这台机器压力会最轻。

nginx支持同时设置多组的负载均衡,用来给不用的server来使用。

负载均衡之多个服务器配置

首先需要安装nginx服务器,比如这里有三个tomcat服务器,地址如下:

  39.108.98.36:80;

​ 39.108.98.37:80;

​ 39.108.98.38:80;

其中nginx安装在39.108.98.36上面,如果只有一个服务器测试,也可以在一个服务器上运行多个tomcat开多个端口来实现,这样也能提升性能

首先看nginx配置,在nginx.conf中http {}块内并且server {}块之外添加如下配置:

upstream backend {
server 39.108.98.37:80;
server 39.108.98.38:80;
}


上面的backend是集群的名字,可以自己命名, 我这里没有指定负载方式,默认使用轮询方式. 配置这个之后,需要在server {}中添加location配置拦截请求并转发给后端的集群,最简单的配置如下:

location / {
proxy_pass  http://backend; proxy_set_header  X-Real-IP  $remote_addr;
root   html;
index  index.html index.htm;
}


这样配置之后保存并重新载入,然后对于所有的请求都会转发到这个集群指定的机器处理了

具体配置情况如下:



访问一下 http://39.108.98.36:81/ 效果如下, 再次刷新之后就显示另一个web节点的项目, 以此达到了负载均衡的目的:





9.Nginx服务状态监控

在Nginx的插件模块中有一个模块stub_status可以监控Nginx的一些状态信息,默认安装可能没有这个模块,手动编译的时候加一下即可。

1)模块安装

先使用命令查看是否已经安装这个模块: –with-http_stub_status_module

[root@iZwz98b01mzud1ytnw5g22Z nginx]# cd /usr/local/nginx/sbin (一定要进到这个目录下)
[root@iZwz98b01mzud1ytnw5g22Z sbin]# ls
nginx
[root@iZwz98b01mzud1ytnw5g22Z sbin]# ./nginx -v (小写是只查看nginx版本号)
nginx version: nginx/1.13.8
[root@iZwz98b01mzud1ytnw5g22Z sbin]# ./nginx -V (V大写会显示版本号和模块等信息)
nginx version: nginx/1.13.8
built by gcc 4.4.7 20120313 (Red Hat 4.4.7-18) (GCC)
built with OpenSSL 1.0.1e-fips 11 Feb 2013
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-pcre=/usr/local/pcre-8.41
[root@iZwz98b01mzud1ytnw5g22Z sbin]#


如果已经安装,会在显示的信息中包含 –with-http_stub_status_module信息。如果没有此模块,需要重新安装,编译命令如下:

./configure –with-http_stub_status_module


2)Nginx配置

安装后只要修改nginx配置即可,在server块中添加如下配置:

location /status{
stub_status on ;
access_log  off;
}




3) 状态查看

配置完成后在浏览器中输入http://39.108.98.36:81/status查看,显示信息如下:



4)参数说明

active connections – 活跃的连接数量

server accepts handled requests — 总共处理了11个连接 , 成功创建11次握手, 总共处理了11个请求

每个连接有三种状态waiting、reading、writing

reading : 读取客户端的Header信息数.这个操作只是读取头部信息,读取完后马上进入writing状态,因此时间很短。

writing : 响应数据到客户端的Header信息数.这个操作不仅读取头部,还要等待服务响应,因此时间比较长。

waiting : 开启keep-alive后等候下一次请求指令的驻留连接.

正常情况下waiting数量是比较多的,并不能说明性能差。反而如果reading+writing数量比较多说明服务并发有问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: