lnmp的搭建——Nginx

搭建之前,我们先设置我们的环境,封装一台母本虚拟机,创建两台快照虚拟机

封装母本虚拟机

1./etc/udev/rules.d/70-persistent-net.rule  (必做)
    系统加载网卡驱动后会去读一个文件/etc/udev/rules.d/70-persistent-net.rule,这个文件是一个缓存文件,包含网卡的mac地址,如果现有网卡的mac地址和文件里的不同,系统会拒绝启动,把文件删除就好了
2.修改ip (必做)
    DEVICE="eth0"
    BOOTPROTO="static"
    ONBOOT="yes"
    IPADDR=172.25.90.1
    PREFIX=24
    GATEWAY=172.25.90.250
    重启网络
    /etc/init.d/network restart
    ping 一下真机,看网络通不通
    若不通,看真机
    # ip addr show br0
    inet 172.25.90.250/24 brd 172.25.90.255 scope global br0
    若是没有上面的这个网段,就添加
    brctl addif br0 vnet0
    ip addr show    #查看vnet0的状态,如果是DOWN的话就执行下面这条命令
    ip link set up vnet0
    现在再ping应该就可以通了   

3.删掉根目录下的东西
4.修改主机名 (必做)
    /etc/sysocnfig/network
5.写解析
    /etc/hosts
6.配置yum源 (必做)
配置完之后再安装软件时,什么也安装不上,报下面的信息
This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.
enable=0

7.
    cd /etc/ssh
    rm -fr ssh_host_*

8.安装一些自己常用的一些软件
    yum install vim lftp openssh-clients -y

9.防火墙以及selinux的关闭
    chkconfig iptables off
    /etc/init.d/iptables stop
    vim /etc/sysconfig/selinux

10.删除ssh密钥
    rm -fr /etc/ssh/ssh_host_*
之后就直接poweroff,这样母本虚拟机就封装好了,注意封装好之后就不要再开启他了,也不要对他做任何的修改

新建两台快照虚拟机
cd /var/lib/libvirt/images
# qemu-img create -f qcow2 -b test.qcow2 vm1
# qemu-img create -f qcow2 -b test.qcow2 vm2

如果虚拟机坏掉
# rm -fr vm1
# qemu-img create -f qcow2 -b test.qcow2 vm1

vm1放的是快照虚拟机自己的一些改变,母本虚拟机没有任何变化

一、Nginx的安装配置


1.下载安装包

# wget http://nginx.org/download/nginx-1.12.0.tar.gz           ##注意下载一定要下载stable的
2.解包
# tar zxf nginx-1.12.0.tar.gz
# cd nginx-1.12.0/src/core         
# vim nginx.h                              
    #define NGINX_VER          "nginx"            ##隐藏Nginx的版本号
# cd nginx-1.12.0/auto/cc                           
# vim gcc
    /debug                 ##搜索debug,把debug下面的哪行注释掉,注释debug可以减小安装后的大小

3.开始编译:
# ./configure --prefix=/usr/local/lnmp/nginx --with-http_ssl_module --with-http_stub_status_module --with-threads --with-file-aio

--prefix=/usr/local/lnmp/nginx                ##指定安装路径

--with-http_ssl_module                          ##启用SSL支持并且能够处理HTTPS请求

--with-http_stub_status_module            ##启用”server status”(服务状态)页

--with-threads                                        ##引入线程池

--with-file-aio                                         ##启用file aio支持(一种APL文件传输格式)

编译中出现的错误
./configure: error: C compiler cc is not found          ##c编译器没有安装
# yum install gcc -y
./configure: error: the HTTP rewrite module requires the PCRE library.     ##pcre库没有安装
# yum install pcre-devel -y
./configure: error: SSL modules require the OpenSSL library.                    ##openssl库没有安装
# yum install openssll-devel -y

4.编译成功之后,开始安装
# make
# make install
5.创建符号链接

# ln -s /usr/local/lnmp/nginx/sbin/nginx /usr/sbin/nginx

二、nginx.conf文件

Nginx的配置有着几个不同的上下文
    main:对任何功能都生效的配置,user,group,worker
    http:只对web服务器有效
    mail:对邮件服务器有效
    server:一般必须属于http
    upstream:实现定义反向代理
    location:属于server(还有)

user www www;         #定义Nginx运行的用户和用户组

worker_processes  2;                       ##nginx进程数,建议设置为等于CPU总核心数。
events
{
use epoll;                                   #参考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ];
worker_connections 65535;       #单个进程最大连接数(最大连接数=连接数*进程数)
}
worker_cpu_affinity 01 10;       ##表示开启两个进程,第一个进程对应着第一个CPU内核,第二个进程对应着第二个CPU内核

                   所能接收的连接数是worker_processes*worker_connections

http() {
        include       mime.types;                ##所包含的文件
        default_type  application/octet-stream;    ##默认支持的类型
        sendfile        on;                        ##打开sendfile功能
        #tcp_nopush     on;                        ##
    }
    nodelay和nopush:
        nodelay:当发送端要发送大量包含少量数据的数据报时,先发送一个小包,将后面到达的少量字符都缓存起来
        而不立即发送,直到收到接收端对前一个数据报报文的ACK确认,或当前字符属于紧急数据,货值积攒到了一定
        数量的数据(比如缓存的字符数据已经达到数据包报文段的最大长度)等多种情况才将其组成一个较大的包发送出去
        nopush:不做推送
       

keepalive_timeout  65;                        ##使用长链接并使用超时
#gzip  on;                                    ##发送给用户的东西都是先压缩再发送,可节省带宽
server{                         ##每个server定义一个虚拟主机,就一个主机都要定义在server
     listen       80;            ##
     server_name  localhost;        ##两个名字监听到同一个地址,端口,就是基于虚拟主机
}
location:   

location /URI/ {            ##/URI/是指下面URL的第三个/
      root "/web/htdocs";        ##相对于URI的网页位置路径,/wen/htdocs映射为/URI/,直接输入域名时,所在的路径,若写的是相对路径,是相对于nginx的默认安装目录
      index index.html;        ##默认访问资源
}
    
     URL举例: http://www.magedu.com/index.html
用法:location [ = | ~ | ~* | ^~ ] uri {...}:
        location URI {}:
            对当前路径及子路径下的所有对象都生效
        location = location {}:
            精确匹配指定的路径,不包括子路径,因此,只对当前资源生效
        location ~* URI {}:
        location ~ URI {}:
            模式匹配URI,此处的URI可使用正则表达式,~区分字符大小写,~不区分大小写
    
        location ^~ URI {} :
            不使用正则表达式
            
        优先级:=,^~,~,~*,URI
    当URI有正则表达式匹配,则下面只能写ip或域名,后面不能目录,否则会报错
    43         location ~* ^/forum {
    44             proxy_pass http://123.207.5.36;
    45         }
    
    httpd:
        <DocumentRoot "">
            #定义网页页面在哪,基于本地文件系统路径做访问控制
                http://www.magedu.com/... 自/...前面的就是由DocumentRoot定义
        </DocumentRoot>
        
        <Location "/bbs">
            #基于URI路径,
                http://www.magedu.com/...  从/...这开始就是URI路径
        </Location>

三、Nginx的简单配置

1.nginx下配置https ssl
 
  [root@VM_83_99_centos ssl]# vim /usr/local/nginx/conf/nginx.conf           ##配置https的虚拟主机
 109     server {
110         listen       443;
111         server_name  localhost;
112
113         ssl                 on;
114         ssl_certificate      /etc/nginx/ssl/nginx.crt;
115         ssl_certificate_key  /etc/nginx/ssl/nginx.key;
116
117         ssl_session_cache    shared:SSL:1m;
118         ssl_session_timeout  5m;
119
120         ssl_ciphers  HIGH:!aNULL:!MD5;
121         ssl_prefer_server_ciphers  on;
122
123         location / {
124             root   /web/htdocs;
125             index  index.html index.htm;
126         }
127     }


生成证书:

[root@VM_83_99_centos conf]# cd /etc/pki/CA/                        
[root@VM_83_99_centos CA]# (umask 077;openssl genrsa 2048 > private/cakey.pem)
[root@VM_83_99_centos CA]# openssl req -new -x509 -key private/cakey.pem -out cacert.pem
    You are about to be asked to enter information that will be incorporated
    into your certificate request.
    What you are about to enter is what is called a Distinguished Name or a DN.
    There are quite a few fields but you can leave some blank
    For some fields there will be a default value,
    If you enter '.', the field will be left blank.
    -----
    Country Name (2 letter code) [XX]:CN
    State or Province Name (full name) []:HA
    Locality Name (eg, city) [Default City]:ZZ
    Organization Name (eg, company) [Default Company Ltd]:Magedu
    Organizational Unit Name (eg, section) []:Tech
    Common Name (eg, your name or your server's hostname) []:ca.magedu.com
    Email Address []:caadmin@magedu.com
[root@VM_83_99_centos CA]# ls
cacert.pem  certs  crl  newcerts  private
[root@VM_83_99_centos CA]# touch serial
[root@VM_83_99_centos CA]# echo 01 > serial          #生成记录已签署证书的个数
[root@VM_83_99_centos CA]# touch index.txt          
[root@VM_83_99_centos CA]# ls   
cacert.pem  certs  crl  index.txt  newcerts  private  serial
[root@VM_83_99_centos CA]# cd /etc/nginx/ssl
[root@VM_83_99_centos ssl]# (umask 077;openssl genrsa 1024 > nginx.key)
[root@VM_83_99_centos ssl]# openssl req -new -key nginx.key -out nginx.csr
    You are about to be asked to enter information that will be incorporated
    into your certificate request.
    What you are about to enter is what is called a Distinguished Name or a DN.
    There are quite a few fields but you can leave some blank
    For some fields there will be a default value,
    If you enter '.', the field will be left blank.
    -----
    Country Name (2 letter code) [XX]:CN  
    State or Province Name (full name) []:HA
    Locality Name (eg, city) [Default City]:ZZ
    Organization Name (eg, company) [Default Company Ltd]:Magedu
    Organizational Unit Name (eg, section) []:Tech
    Common Name (eg, your name or your server's hostname) []:www.magedu.com
    Email Address []:

    Please enter the following 'extra' attributes
    to be sent with your certificate request
    A challenge password []:
    An optional company name []:
[root@VM_83_99_centos ssl]# openssl ca -in nginx.csr -out nginx.crt -days 3650
    Using configuration from /etc/pki/tls/openssl.cnf
    Check that the request matches the signature
    Signature ok
    Certificate Details:
            Serial Number: 1 (0x1)
            Validity
                Not Before: Apr 11 14:40:15 2017 GMT
                Not After : Apr  9 14:40:15 2027 GMT
            Subject:
                countryName               = CN
                stateOrProvinceName       = HA
                organizationName          = Magedu
                organizationalUnitName    = Tech
                commonName                = www.magedu.com
            X509v3 extensions:
                X509v3 Basic Constraints:
                    CA:FALSE
                Netscape Comment:
                    OpenSSL Generated Certificate
                X509v3 Subject Key Identifier:
                    02:D3:A0:CE:63:83:C5:D8:CC:B4:1C:8C:AB:4C:3B:76:1C:B5:6A:95
                X509v3 Authority Key Identifier:
                    keyid:5C:52:9F:7F:0A:56:47:22:D2:F9:01:81:B0:55:6D:10:3A:54:2F:56

    Certificate is to be certified until Apr  9 14:40:15 2027 GMT (3650 days)
    Sign the certificate? [y/n]:y       


    1 out of 1 certificate requests certified, commit? [y/n]y
    Write out database with 1 new entries
    Data Base Updated
[root@VM_83_99_centos ssl]# /usr/local/nginx/sbin/nginx -s reload            ##重载nginx
[root@VM_83_99_centos ssl]# netstat -tnlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name   
tcp        0      0 0.0.0.0:80                  0.0.0.0:*                   LISTEN      7179/nginx          
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      868/sshd            
tcp        0      0 127.0.0.1:25                0.0.0.0:*                   LISTEN      956/master          
tcp        0      0 0.0.0.0:443                 0.0.0.0:*                   LISTEN      7179/nginx          


2.配置Nginx的虚拟主机
[root@VM_83_99_centos ssl]# vim /usr/local/nginx/conf/nginx.conf    ##在一个server里定义一个虚拟主机
 37         server_name  www.xiyou.com;
  92     server {
 93         listen 80;
 94         server_name www.a.org;
 95         location / {
 96             root /web/a.org;
 97             index index.html;
 98         }
 99     }
 
 [root@VM_83_99_centos ssl]# mkdir /web/a.org        ##创建虚拟主机的测试页目录
[root@VM_83_99_centos ssl]# vim /web/a.org/index.html    ##编写测试页
[root@VM_83_99_centos ssl]# nginx -t                ##检查是否写的有语法错误
-bash: nginx: command not found
[root@VM_83_99_centos ssl]# service nginx configtest    ##检查是否有语法错误
nginx: unrecognized service
[root@VM_83_99_centos ssl]# /usr/local/nginx/sbin/nginx -s reload    ##重启服务
[root@VM_83_99_centos ssl]# vim /etc/hosts        ##编写本地解析文件
  2 123.207.5.36    www.xiyou.com
  3 123.207.5.36    www.a.org
[root@VM_83_99_centos ssl]# curl http://www.xiyou.com        ##测试
<h1>Test Page </h1>
[root@VM_83_99_centos ssl]# curl http://www.a.org
a.org



3.实现基于IP地址的访问控制
        在某个location内定义deny,allow
    基于用户访问控制:
        需要借助于httpd来创建用户,必须确保他不要开机启动,否则会和Nginx征用同一个套接字
        [root@VM_83_99_centos sbin]# vim ../conf/nginx.conf
         53         auth_basic "hhhh";
         54         auth_basic_user_file /etc/nginx/.users;
        
        [root@VM_83_99_centos sbin]# yum install httpd -y
        [root@VM_83_99_centos sbin]# chkconfig --list httpd
        [root@VM_83_99_centos sbin]# mkdir /etc/nginx/
        [root@VM_83_99_centos sbin]# htpasswd -c -m /etc/nginx/.users tom
        New password:
        Re-type new password:
        Adding password for user tom
        [root@VM_83_99_centos sbin]# htpasswd -m /etc/nginx/.users jerry        ##千万注意:第二次不能用-c
        New password:
        Re-type new password:
        Adding password for user jerry
        
        
    autoindex:
        [root@VM_83_99_centos sbin]# vim ../conf/nginx.conf
         48         location /bbs {
         49             root /web;
         50             index 1.html;
         51             autoindex on;         #开启目录列表访问,合适下载类型的服务器(FTP),默认关闭。
         52         }
         [root@VM_83_99_centos sbin]# ./nginx -s reload


stub_status:        
[root@VM_83_99_centos conf]# vim nginx.conf
 43         location / {
 44             root   /web/htdocs;
 45             index  index.html index.htm;
 46         }
 47
 48         location /status {
 49             stub_status on;              #启用stub_status的工作状态统计功能
 50         }
 51
 52         location /bbs {
 53             root /web;
 54             index index.html;
 55             autoindex on;
 56         }
 [root@VM_83_99_centos conf]# ../sbin/nginx -s reload
 测试:
 Active connections: 2
server accepts handled requests
 135 135 221
Reading: 0 Writing: 1 Waiting: 1

上面的三个数字分别是:已经接受连接的个数,已经处理的连接的个数,已经处理的请求的个数(一个长链接可处理多个请求)
Reading:nginx正在读请求首部的个数,即正在接进来的请求的个数
Writing:nginx正在读请求主体的请求的个数,或正处理着请求内容的请求的个数,或者正在想其客户端发送响应的个数
waiting:长链接模式的保持的连接个数


4.反向代理加负载均衡


再创建两台虚拟机,都安装上apache,并将服务开启
修改nginx的配置文件,在http段定义一组上游服务器

upstream westos {                      
                server 172.25.90.2:80 weight=2;                  ##这台服务器收到的请求数是下面那台服务器的2倍
                server 172.25.90.3:80;
                server 172.25.90.1:8080 backup;                 ##如果两台服务器都宕掉,就定向到这台服务器来处理
 }
在虚拟主机上
server {
        listen 80;
        server_name www.w2.com;

        location / {
                proxy_pass http://westos;         ##反向代理到westos这组服务器上
        }
}
查看效果
# for i in {1..10}; do curl www.w2.com; done
可以模拟一台虚拟机宕掉,两台都宕掉的结果是什么


当启动httpd服务器时报错
Starting httpd: httpd: Could not reliably determine the server's fully qualified domain name, using 172.25.90.2 for ServerName
解决办法:
    vim /etc/httpd/conf/httpd.conf
    把ServerName修改正确就好


负载均衡算法:
        round-robin:默认,如果服务器有权重就使用它,如果没有权重就不参加负载均衡:
        ip_hash:每个请求按访问ip的hash结果分配,这样每个访客固定访问一个后端服务器,可以解决session的问题。 

        least_conn:我们知道轮询算法是把请求平均的转发给各个后端,使它们的负载大致相同。这有个前提,就是每个请求所占用的后端时间要差不多,如果有些请求占用的时间很长,会导致其所在的后端负载较高。在这种场景下,把请求转发给连接数较少的后端,能够达到更好的负载均衡效果,这就是least_conn算法。



5.重定向
server {
        listen 80;
        server_name www.w1.com;
        rewrite ^(.*) https://$server_name$1 permanent;           #永久定向到www.w1.com
}


sysctl命令被用于在内核运行时动态地修改内核的运行参数,可用的内核参数在目录/proc/sys中。它包含一些TCP/ip堆栈和虚拟内存系统的高级选项

来自: http://man.linuxde.net/sysctl
sysctl命令被用于在内核运行时动态地修改内核的运行参数,可用的内核参数在目录/proc/sys中。它包含一些TCP/ip堆栈和虚拟内存系统的高级选项

来自: http://man.linuxde.net/sysctl
sysctl命令被用于在内核运行时动态地修改内核的运行参数,可用的内核参数在目录/proc/sys中。它包含一些TCP/ip堆栈和虚拟内存系统的高级选项

来自: http://man.linuxde.net/sysctl


实验1:怎么将某客户端的请求转发给后端服务器时,请求者还是客户端,而不是Nginx服务器?
    
    参数:proxy_set_header X-Real-IP $remot_addr;
    让后端服务器的日志记录的是客户端地址,而不是代理服务器地址:
    编辑(http服务安装位置)/etc/http/conf/httpd.conf,找logformat
    %{X-Real-IP}i
    
实验2:如何把所有的访问都转发到后端


Nginx代理请求到多个服务器:
    upstream:上游服务器
    upstream要定义在server之外
    upstream websrvs {
        server 172.26.100.11 weight=1;
        server 172.26.100.12 weight=1;
    }
    还要将反向代理修改为websrvs
    proxy_pass http://websrvs;
    
    upstream的健康状况检查:
        upstream websrvs {
        server 172.26.100.11 weight=1 max_fails=2 fail_timeout=2;
        server 172.26.100.12 weight=1 max_fails=2 fail_timeout=2;
    }
   
    upstream内还可以填ip_bash:这个参数表示记录客户端在哪个服务器上得到的请求,以后就一直到那个后端服务器上访问
 

sysctl命令:sysctl是一个允许您改变正在运行中的Linux系统的接口。它包含一些 TCP/IP 堆栈和虚拟内存系统的高级选项, 这可以让有经验的管理员提高引人注目的系统性能。


查看所有可读变量:
# sysctl -a    

ulimit命令:http://www.linuxidc.com/Linux/2012-10/72782.htm


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值