万字长文带你了解nginx的安装与使用

概述

Nginx是一个高性能的HTTP和反向代理服务器,特点是占有内存少,并发能力强,事实上Nginx的并发能力确实在同类型的网页服务器中表现特别出色。常见的软件代理服务还有HA proxy、Varnish和Squid等。

nginx的安装

安装nginx的依赖

yum install -y gcc gcc-c++ make libtool wget pcre pcre-devel zlib zlib-devel openssl openssl-devel

在这里插入图片描述

下载nginx

 wget http://nginx.org/download/nginx-1.23.1.tar.gz

在这里插入图片描述

解压压缩包

tar -zxvf  nginx
cd nginx-1.23.1/

在这里插入图片描述

安装

 ./configure
 make && make install

注意:安装完成后的路径为:/usr/local/nginx

启动

/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf

在本地浏览器访问80端口,看到如下画面,说明nginx启动成功。如果网络不通,请注意检查linux的防火墙是否开启。
在这里插入图片描述

常用命令

普通启动服务:/usr/local/nginx/sbin/nginx

配置文件启动:/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf

暴力停止服务:/usr/local/nginx/sbin/nginx -s stop

优雅停止服务:/usr/local/nginx/sbin/nginx -s quit

检查配置文件:/usr/local/nginx/sbin/nginx -t

重新加载配置:/usr/local/nginx/sbin/nginx -s reload

查看相关进程:ps -ef | grep nginx

测试反向代理

实现目标如下图所示,nginx监听80端口,并把请求转发到8080,在服务端启动一个tomcat监听8080用于测试。
在这里插入图片描述

nginx配置修改

修改nginx配置

 vi /usr/local/nginx/conf/nginx.conf
 server {
        listen       80;
        server_name  192.168.0.109;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            proxy_pass http://127.0.0.1:8080;
            root   html;
            index  index.html index.htm;
        }

tomcat

下载tomcat

wget http://archive.apache.org/dist/tomcat/tomcat-8/v8.0.23/bin/apache-tomcat-8.0.23.tar.gz

解压

tar -zxvf apache-tomcat-8.0.23.tar.gz

启动

/usr/local/tomcat/bin/startup.sh

这里为了方便,直接关闭服务器的防火墙

 /usr/local/tomcat/bin/shutdown.sh

测试:
在本地浏览器输入 http://192.168.0.109/,页面展示如下即代理成功。
在这里插入图片描述
关闭tomcat

/usr/local/tomcat/bin/shutdown.sh

测试根据不同url分别路由

在这里插入图片描述

nginx配置修改



    server {
        listen       80;
        server_name  192.168.0.109;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location ~/edu/ { 
            proxy_pass  http://127.0.0.1:8080;
            root   html;
            index  index.html index.htm;
        }
        location ~/pro/{
            proxy_pass http://127.0.0.1:8081;
        }

        #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;
        }

tomcat

拷贝另一个tomcat

cp -r tomcat /usr/local/tomcat2

更改tomcat2的配置文件,修改端口号为8081

rm -f /usr/local/tomcat2/conf/server.xml
vi /usr/local/tomcat2/conf/server.xml

拷贝如下内容到server.xml中

<?xml version='1.0' encoding='utf-8'?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 -->
<Server port="8006" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.startup.VersionLoggerListener" />
  <!-- Security listener. Documentation at /docs/config/listeners.html
  <Listener className="org.apache.catalina.security.SecurityListener" />
  -->
  <!--APR library loader. Documentation at /docs/apr.html -->
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />

  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>

  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container",
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <Service name="Catalina">

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->


    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
    -->
    <Connector port="8081" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8444" />
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    -->
    <!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443
         This connector uses the NIO implementation that requires the JSSE
         style configuration. When using the APR/native implementation, the
         OpenSSL style configuration is required as described in the APR/native
         documentation -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
               maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" />
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="8010" protocol="AJP/1.3" redirectPort="8444" />


    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine name="Catalina" defaultHost="localhost">

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->

      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>

      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />

      </Host>
    </Engine>
  </Service>
</Server>

启动两个tomcat

/usr/local/tomcat/bin/startup.sh
/usr/local/tomcat2/bin/startup.sh

测试

在本地浏览器访问http://192.168.0.109/pro/a.html 出现
在这里插入图片描述

在本地浏览器访问http://192.168.0.109/edu/a.html 出现
在这里插入图片描述
说明根据不同url分别路由成功。

测试负载均衡

当输入同一个uri时,nginx会根据负载均衡策略将报文分别打到不同的服务中。
在这里插入图片描述

修改nginx配置文件

vi /usr/local/nginx/conf/nginx.conf


upstream myserver {
        server 192.168.206.128:8080;
        server 192.168.206.128:8081;
    }

    server {
        listen       80;
        server_name  192.168.206.128;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            proxy_pass http://myserver;
        }

负载均衡策略讲解

默认 轮询
upstream myserver {
        server 192.168.206.128:8080;
        server 192.168.206.128:8081;   
 }
 权重分配,权重越大访问的可能性就越大,权重与访问的比率成正比
 upstream myserver {
        server 192.168.206.128:8080 weight=1;
        server 192.168.206.128:8081 weight=10;   
 }

hash 根据客户端的ip地址进行hash,将请求固定打到某个后端服务中,这是解决服务端间session无法同步的一个思路
 upstream myserver {
 		
        server 192.168.206.128:8080 weight=1;
        server 192.168.206.128:8081 weight=10;   
 }
按后端服务器的响应时间来分配请求,响应时间短的优先分配。例如:
 upstream myserver {
 		
        server 192.168.206.128:8080 ;
        server 192.168.206.128:8081;   
		fair;        
 }

修改tomcat配置

在Tomcat2的webapps文件夹中,创建一个edu文件夹,在里边创建a.html
并分别启动两个tomcat

mkdir -p /usr/local/tomcat2/webapps/edu
echo "<h1>This is 8081 Port</h1>" > /usr/local/tomcat2/webapps/edu/a.html
/usr/local/tomcat1/bin/startup.sh
/usr/local/tomcat2/bin/startup.sh

测试

在浏览器中多次点击http://192.168.0.109/edu/a.html,会依次展示如下页面。
在这里插入图片描述
在这里插入图片描述

动静分离

目前主流的访问静态资源的方案是通过CDN进行加速,但是nginx也是可以进行访问静态资源的,如果动态资源和静态资源同时存在,nginx会优先去访问静态资源。

配置文件

        listen       80;
        server_name  192.168.0.109;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location /www/ {
            root /data/;
            index index.html index.htm;
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值