1. Install NGINX on Linux
Under Centos, the yum source does not provide nginx installation, you can switch Obtain and install using the yum source method. You can also directly download the installation package. The following commands require root permissions to execute: first install the necessary libraries (the gzip module in nginx requires the zlib library, the rewrite module requires the pcre library, and the ssl function requires the openssl library). Select /usr/local as the installation directory, and the following specific version numbers will change based on actual conditions.
1.1. Install PCRE library
$ cd /usr/local/ $ wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.36.tar.gz $ tar -zxvf pcre-8.36.tar.gz $ cd pcre-8.36 $ ./configure $ make $ make install
./configure error reporting(recommended learning: nginx tutorial)
configure: error: You need a C++ compile r for C++ support.
Solution: yum install -y gccgcc-c
1.2. Install zlib library
$ cd /usr/local/ $ wget http://zlib.net/zlib-1.2.8.tar.gz $ tar -zxvf zlib-1.2.8.tar.gz $ cd zlib-1.2.8 $ ./configure $ make $ make install
1.3. Install ssl
$ cd /usr/local/ $ wget http://www.openssl.org/source/openssl-1.0.1j.tar.gz $ tar -zxvf openssl-1.0.1j.tar.gz $ ./config $ make $ make install
1.3. Install NGINX
$ cd /usr/local/ $ wget http://nginx.org/download/nginx-1.8.0.tar.gz $ tar -zxvf nginx-1.8.0.tar.gz $ cd nginx-1.8.0 $ ./configure --prefix=/usr/local/nginx $ make $ make install
Common installation errors:
Nginx startup prompt cannot find libpcre.so.1 solution
If it is a 32-bit system
[root@lee ~]# ln -s /usr/local/lib/libpcre.so.1 /lib
If it is a 64-bit system
[root@lee ~]# ln -s /usr/local/lib/libpcre.so.1 /lib64
Then start nginx It’s OK
[root@lee ~]# /usr/local/webserver/nginx/sbin/nginx
1.4. Start NGINX
$ /usr/local/nginx/sbin/nginx
Open the browser to access the IP of this machine. If the browser displays Welcome to nginx!, it means that Nginx has been installed and Run successfully.
2. Common NGINX commands
重启: $ /usr/local/nginx/sbin/nginx 启动命令 重启: $ /usr/local/nginx/sbin/nginx –s reload 停止: $ /usr/local/nginx/sbin/nginx –s stop 测试配置文件是否正常: $ /usr/local/nginx/sbin/nginx –t 强制关闭: $ pkillnginx
3. Start Nginx Keepalived
3.1. What is Keepalived
Keepalived is a free and open source software written in C similar to layer3, 4 & 7 switching mechanism. It has the functions of layer 3, layer 4 and layer 7 switches that we usually talk about. . It mainly provides loadbalancing (load balancing) and high-availability (high availability) functions. The implementation of load balancing requires relying on Linux's virtual service kernel module (ipvs), while high availability is through VRRP The protocol implements failover services between multiple machines.
The above picture is the functional architecture of Keepalived, which is roughly divided into two layers: user space and kernel space.
Kernel space: Mainly includes two parts: IPVS (IP virtual server, used to realize load balancing of network services) and NETLINK (providing advanced routing and other related network functions).
User Space:
- WatchDog: Load monitoring checkers and the status of the VRRP process
- VRRP Stack: Load between load balancers FailOver, VRRP is not necessary if only one load equalizer is used.
- Checkers: Responsible for health checking of the real server, which is the main function of keepalived. In other words, there can be no VRRP Stack, but healthchecking is a must.
- IPVS wrapper: The user sends the set rules to the kernel ipvs code
- Netlink Reflector: used to set the vip address of vrrp, etc.
All functions of Keepalived are implemented by configuring the keepalived.conf file.
3.2. Install Keepalived
Download keepalived address: http://www.keepalived.org/download.html
Unzip and install:
tar -zxvf keepalived-1.2.18.tar.gz -C /usr/local/ yum install -yopensslopenssl-devel(需要安装一个软件包) cd keepalived-1.2.18/ && ./configure --prefix=/usr/local/keepalived make&& make install
3.3. Install Keepalived as a Linux system service
将keepalived安装成Linux系统服务,因为没有使用keepalived的默认安装路径(默认路径:/usr/local),安装完成之后,需要做一些修改工作: 首先创建文件夹,将keepalived配置文件进行复制: mkdir /etc/keepalived cp /usr/local/keepalived/etc/keepalived/keepalived.conf /etc/keepalived/ 然后复制keepalived脚本文件: cp /usr/local/keepalived/etc/rc.d/init.d/keepalived /etc/init.d/ cp /usr/local/keepalived/etc/sysconfig/keepalived /etc/sysconfig/ ln -s /usr/local/sbin/keepalived /usr/sbin/ ln -s /usr/local/keepalived/sbin/keepalived /sbin/ 可以设置开机启动:chkconfigkeepalived on,到此我们安装完毕!
3.4. Common Keepalived commands
servicekeepalived start servicekeepalived stop
4. Keepalived configuration
4.1. Configure NGINX’s active and backup automatic restart
1. Modify the configuration file:vim /etc /keepalived/keepalived.conf
1) Modify master NGINX configuration
<span style="color: #000000;">! Configuration File for keepalived global_defs { router_id bhz005 ##标识节点的字符串,通常为hostname } ## keepalived会定时执行脚本并且对脚本的执行结果进行分析,动态调整vrrp_instance的优先级。这里的权重weight 是与下面的优先级priority有关,如果执行了一次检查脚本成功,则权重会-20,也就是由100 - 20 <br>变成了80,Master 的优先级为80 就低于了Backup的优先级90,那么会进行自动的主备切换。 如果脚本执行结果为0并且weight配置的值大于0,则优先级会相应增加。 如果脚本执行结果不为0 并且weight配置的值小于0,则优先级会相应减少。 vrrp_scriptchk_nginx { script "/etc/keepalived/nginx_check.sh" ##执行脚本位置 interval 2 ##检测时间间隔 weight -20 ## 如果条件成立则权重减20(-20) } ## 定义虚拟路由 VI_1为自定义标识。 vrrp_instance VI_1 { state MASTER ## 主节点为MASTER,备份节点为BACKUP ## 绑定虚拟IP的网络接口(网卡),与本机IP地址所在的网络接口相同(我这里是eth6) interface eth6 virtual_router_id 172 ## 虚拟路由ID号 mcast_src_ip 192.168.1.172 ## 本机ip地址 priority 100 ##优先级配置(0-254的值) Nopreempt ## advert_int 1 ## 组播信息发送间隔,俩个节点必须配置一致,默认1s authentication { auth_type PASS auth_passbhz ## 真实生产环境下对密码进行匹配 } track_script { chk_nginx } virtual_ipaddress { 192.168.1.170 ## 虚拟ip(vip),可以指定多个 } }</span>
2) Modify Backup NGINX configuration
! Configuration File for keepalived global_defs { router_id bhz006 } vrrp_scriptchk_nginx { script "/etc/keepalived/nginx_check.sh" interval 2 weight -20 } vrrp_instance VI_1 { state BACKUP interface eth7 virtual_router_id 173 mcast_src_ip 192.168.1.173 priority 90 ##优先级配置 advert_int 1 authentication { auth_type PASS auth_passbhz } track_script { chk_nginx } virtual_ipaddress { 192.168.1.170 } }
3) nginx_check.sh script
#!/bin/bash A=`ps -C nginx–no-header |wc -l` if [ $A -eq 0 ];then /usr/local/nginx/sbin/nginx sleep 2 if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then killallkeepalived fi fi
4) Then copy the master's keepalived configuration file to the /etc/keepalived/ folder of the master machine (172), and then copy the backup's keepalived configuration file to the /etc/keepalived/ of the backup machine (173). folder, and finally copy the nginx_check.sh script to the /etc/keepalived/ folder of the two machines.
5) nginx_check.sh script authorization. Grant executable permissions: chmod x /etc/keepalived/nginx_check.sh
6) After starting nginx on 2 machines. Let’s start keepalived
/usr/local/nginx/sbin/nginx servicekeepalived start ps -ef | grepnginx ps -ef | grepkeepalived
7 on both machines. Take a look at the IP addresses of the two machines. A virtual IP will appear under the a command. Test without closing Keepalived, kill NGINX, and then observe whether it restarts. Turn off Keepalived, kill NGINX, and then check whether it restarts.
5. Session sharing solution in cluster situation
5.1. What causes session in cluster situation?
Due to session storage On the server side, users in the cluster may access different servers, so sessions may not be shared.
5.2, Session sharing solution
1)NGINX做的负载均衡可以绑定ip_hash,从而使同一个IP访问同一个服务器 ------------------该方案使得集群失去意义。
2)利用数据库同步session----------------------太过复杂
3)利用cookie同步session(保存一个session到本地,再次访问将其带到服务器端)----------------------安全性差、http请求都需要带参数增加了带宽消耗
4)使用session集群,存放到redis中(spring-session)
5.3、spring-session项目,解决session共享问题
<!--spring boot 与redis应用基本环境配置 --> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-redis</artifactid> </dependency> <!--spring session 与redis应用基本环境配置,需要开启redis后才可以使用,不然启动Spring boot会报错 --> <dependency> <groupid>org.springframework.session</groupid> <artifactid>spring-session-data-redis</artifactid> </dependency>
创建SessionConfig
import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; //这个类用配置redis服务器的连接 //maxInactiveIntervalInSeconds为SpringSession的过期时间(单位:秒) @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800) Public class SessionConfig { // 冒号后的值为没有配置文件时,制动装载的默认值 @Value("${redis.hostname:localhost}") String HostName; @Value("${redis.port:6379}") int Port; @Bean Public JedisConnectionFactory connectionFactory() { JedisConnectionFactory connection = new JedisConnectionFactory(); connection.setPort(Port); connection.setHostName(HostName); return connection; } }
初始化Session
//初始化Session配置Public class SessionInitializer extends AbstractHttpSessionApplicationInitializer{ Public SessionInitializer() { super(SessionConfig.class); } }
控制层代码
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestControllerpublic class SessionController { @Value("${server.port}") private String PORT; @RequestMapping("/index") public String index() { return "index:" + PORT; } /** * @methodDesc: 功能描述:(往session存放值) */ @RequestMapping("/setSession") public String setSession(HttpServletRequest request, String sessionKey, String sessionValue) { HttpSession session = request.getSession(true); session.setAttribute(sessionKey, sessionValue); return "success,port:" + PORT; } /** * @methodDesc: 功能描述:(从Session获取值) */ @RequestMapping("/getSession") public String getSession(HttpServletRequest request, String sessionKey) { HttpSession session =null; try { session = request.getSession(false); } catch (Exception e) { e.printStackTrace(); } String value=null; if(session!=null){ value = (String) session.getAttribute(sessionKey); } return "sessionValue:" + value + ",port:" + PORT; } }
六、高并发解决方案
业务数据库 -》 数据水平分割(分区分表分库)、读写分离
业务应用 -》 逻辑代码优化(算法优化)、公共数据缓存
应用服务器 -》 反向静态代理、配置优化、负载均衡(apache分发,多tomcat实例)
系统环境 -》 JVM调优
页面优化 -》 减少页面连接数、页面尺寸瘦身
动态资源和静态资源分离
CDN加速
服务分布式部署
The above is the detailed content of NGINX achieves high availability under Linux. For more information, please follow other related articles on the PHP Chinese website!

NGINX is suitable for handling high concurrent and static content, while Apache is suitable for complex configurations and dynamic content. 1. NGINX efficiently handles concurrent connections, suitable for high-traffic scenarios, but requires additional configuration when processing dynamic content. 2. Apache provides rich modules and flexible configurations, which are suitable for complex needs, but have poor high concurrency performance.

NGINX and Apache each have their own advantages and disadvantages, and the choice should be based on specific needs. 1.NGINX is suitable for high concurrency scenarios because of its asynchronous non-blocking architecture. 2. Apache is suitable for low-concurrency scenarios that require complex configurations, because of its modular design.

NGINXUnit is an open source application server that supports multiple programming languages and provides functions such as dynamic configuration, zero downtime updates and built-in load balancing. 1. Dynamic configuration: You can modify the configuration without restarting. 2. Multilingual support: compatible with Python, Go, Java, PHP, etc. 3. Zero downtime update: Supports application updates that do not interrupt services. 4. Built-in load balancing: Requests can be distributed to multiple application instances.

NGINXUnit is better than ApacheTomcat, Gunicorn and Node.js built-in HTTP servers, suitable for multilingual projects and dynamic configuration requirements. 1) Supports multiple programming languages, 2) Provides dynamic configuration reloading, 3) Built-in load balancing function, suitable for projects that require high scalability and reliability.

NGINXUnit improves application performance and manageability with its modular architecture and dynamic reconfiguration capabilities. 1) Modular design includes master processes, routers and application processes, supporting efficient management and expansion. 2) Dynamic reconfiguration allows seamless update of configuration at runtime, suitable for CI/CD environments. 3) Multilingual support is implemented through dynamic loading of language runtime, improving development flexibility. 4) High performance is achieved through event-driven models and asynchronous I/O, and remains efficient even under high concurrency. 5) Security is improved by isolating application processes and reducing the mutual influence between applications.

NGINXUnit can be used to deploy and manage applications in multiple languages. 1) Install NGINXUnit. 2) Configure it to run different types of applications such as Python and PHP. 3) Use its dynamic configuration function for application management. Through these steps, you can efficiently deploy and manage applications and improve project efficiency.

NGINX is more suitable for handling high concurrent connections, while Apache is more suitable for scenarios where complex configurations and module extensions are required. 1.NGINX is known for its high performance and low resource consumption, and is suitable for high concurrency. 2.Apache is known for its stability and rich module extensions, which are suitable for complex configuration needs.

NGINXUnit improves application flexibility and performance with its dynamic configuration and high-performance architecture. 1. Dynamic configuration allows the application configuration to be adjusted without restarting the server. 2. High performance is reflected in event-driven and non-blocking architectures and multi-process models, and can efficiently handle concurrent connections and utilize multi-core CPUs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
