Keepalive second-build lightweight nginx High Availability

Source: Internet
Author: User
Tags perl script what is nginx

1. Simple Principle description

In the previous blog, we briefly learned what is keepalive and how to implement high availability of keepalive + httpd. We all know that compared with httpd, there are more lightweight nginx services that can provide us with web page capabilities. It can also implement the reverse proxy function. So what is nginx? What advantages and features does it have? Next we will briefly describe it to you.


Traditionally, web Services Based on the process or thread model architecture process concurrent connection requests through each process or thread, which is bound to block network and I/O operations, another inevitable result is low memory or CPU utilization. To generate a new process/thread, prepare its runtime environment in advance, including allocating heap memory and stack memory for it, and creating a new execution context for it. These operations require CPU usage, and too many processes/threads may cause thread jitter or frequent context switching, resulting in further reduction of system performance.


At the initial stage of the design, nginx mainly focused on its high performance and high-density utilization of physical computing resources. Therefore, nginx adopts different architecture models. Inspired by the advanced processing mechanism based on "events" in the design of multiple operating systems, nginx adopts a modular, event-driven, asynchronous, single-thread, and non-blocking architecture, A large number of multiplexing and event notification mechanisms are adopted. In nginx, connection requests are processed by a few worker processes that only contain one thread in an efficient run-loop Mechanism, each worker can process thousands of concurrent connections and requests in parallel.


If the load is dominated by CPU-intensive applications, such as SSL or compression applications, the number of workers should be the same as the number of CPUs; if the load is dominated by IO-intensive, such as responding to a large amount of content to the client, the number of workers should be 1.5 or 2 times of the number of CPUs.


Nginx will run multiple processes at the same time as needed: one master process and several worker processes. When cache is configured, there will also be cache loader processes (cache loader) and cache manager process (cache manager. All processes only contain one thread and communicate with each other through the "Shared Memory" mechanism. The master process runs as the root user, while worker, cache loader, and cache manager run as non-privileged users.

The main process mainly completes the following tasks:

1. Read and verify the configuration information;

2. Create, bind, and close a socket;

3. Number of worker processes started, terminated, and maintained;

4. reconfigure the features without suspending the service;

5. Control Non-disruptive program upgrades, enable new binary programs, and roll back to the old version as needed;

6. re-open the log file to scroll the log;

7. Compile the embedded perl script;


These functions are based on our predecessors to make better improvements. Therefore, we are more inclined to use nginx when implementing simple web applications. Therefore, we provide you with a nginx-based keepalive high-availability platform. Topology: 650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/01363222Z-0.jpg "title =" tuopu.jpg "/>

Ii. install and configure nginx

1. installation plan

Rhel6.4-32 virtual machine host1: 172.16.12.61, host2: 172.16.12.62

2. Resolve Dependencies

To compile and install nginx, you must first install the Development package group "Development Tools" and "Development Libraries ". You also need to install the pcre-devel package. At the same time, you also need to synchronize the time of the two servers:

# Yum-y gourpinstall "Development Tools" "Development Libraries" # yum-y install pcre-devel # ntpdate 172.16.0.1 #172.16.0.1 is the time server set up

3. Install nginx

First, add the user nginx to run the nginx service process:

# groupadd -r nginx# useradd -r -g nginx nginx# tar xf nginx-1.4.1.tar.gz# cd nginx-1.4.1

Then compile and install:

#. /Configure \ -- prefix =/usr \ # installation path -- sbin-path =/usr/sbin/nginx \ # BINARY command -- conf-path =/etc/nginx. conf \ # configuration file -- error-log-path =/var/log/nginx/error. log \ # error log -- http-log-path =/var/log/nginx/access. log \ # access log -- pid-path =/var/run/nginx. pid \ # PID path -- lock-path =/var/lock/nginx. lock \ # lock file -- user = nginx \ # user -- group = nginx \ # group -- with-http_ssl_module \ # support ssl authentication module -- with-http_flv_module \ # support streaming media -- with-http_stub_status_module \ # support statistics page -- with-http_gzip_static_module \ # support page Compression -- http-client-body-temp-path =/var/tmp/nginx/client/\ # user request subject cache directory -- http-proxy-temp -path =/var/tmp/nginx/proxy/\ # proxy data -- http-fastcgi-temp-path =/var/tmp/nginx/fcgi/\ # fastcgi -- http- uwsgi-temp-path =/var/tmp/nginx/uwsgi \ # python framework supported -- http-scgi-temp-path =/var/tmp/nginx/scgi \ # scgi -- with-pcre # make & make install

Note:Some software packages may be installed differently on different machines during the installation process, and different errors may occur during the compilation and installation process. Don't worry, follow the error message to install the required software package. If you have any questions, you can leave a message or search for them online.

4. Provide SysV init script for nginx:

Create a file/etc/rc. d/init. d/nginx with the following content:

#!/bin/sh## nginx - this script starts and stops the nginx daemon## chkconfig:   - 85 15# description:  Nginx is an HTTP(S) server, HTTP(S) reverse \#               proxy and IMAP/POP3 proxy server# processname: nginx# config:      /etc/nginx/nginx.conf# config:      /etc/sysconfig/nginx# pidfile:     /var/run/nginx.pid                                                                                                                                                                                                                                                                                    # Source function library.. /etc/rc.d/init.d/functions                                                                                                                                                                                                                                                                                    # Source networking configuration.. /etc/sysconfig/network                                                                                                                                                                                                                                                                                    # Check that networking is up.[ "$NETWORKING" = "no" ] && exit 0                                                                                                                                                                                                                                                                                    nginx="/usr/sbin/nginx"prog=$(basename $nginx)                                                                                                                                                                                                                                                                                    NGINX_CONF_FILE="/etc/nginx/nginx.conf"                                                                                                                                                                                                                                                                                    [ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx                                                                                                                                                                                                                                                                                    lockfile=/var/lock/subsys/nginx                                                                                                                                                                                                                                                                                    make_dirs() {   # make required directories   user=`nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`   options=`$nginx -V 2>&1 | grep 'configure arguments:'`   for opt in $options; do       if [ `echo $opt | grep '.*-temp-path'` ]; then           value=`echo $opt | cut -d "=" -f 2`           if [ ! -d "$value" ]; then               # echo "creating" $value               mkdir -p $value && chown -R $user $value           fi       fi   done}                                                                                                                                                                                                                                                                                    start() {    [ -x $nginx ] || exit 5    [ -f $NGINX_CONF_FILE ] || exit 6    make_dirs    echo -n $"Starting $prog: "    daemon $nginx -c $NGINX_CONF_FILE    retval=$?    echo    [ $retval -eq 0 ] && touch $lockfile    return $retval}                                                                                                                                                                                                                                                                                    stop() {    echo -n $"Stopping $prog: "    killproc $prog -QUIT    retval=$?    echo    [ $retval -eq 0 ] && rm -f $lockfile    return $retval}                                                                                                                                                                                                                                                                                    restart() {    configtest || return $?    stop    sleep 1    start}                                                                                                                                                                                                                                                                                    reload() {    configtest || return $?    echo -n $"Reloading $prog: "    killproc $nginx -HUP    RETVAL=$?    echo}                                                                                                                                                                                                                                                                                    force_reload() {    restart}                                                                                                                                                                                                                                                                                    configtest() {  $nginx -t -c $NGINX_CONF_FILE}                                                                                                                                                                                                                                                                                    rh_status() {    status $prog}                                                                                                                                                                                                                                                                                    rh_status_q() {    rh_status >/dev/null 2>&1}                                                                                                                                                                                                                                                                                    case "$1" in    start)        rh_status_q && exit 0        $1        ;;    stop)        rh_status_q || exit 0        $1        ;;    restart|configtest)        $1        ;;    reload)        rh_status_q || exit 7        $1        ;;    force-reload)        force_reload        ;;    status)        rh_status        ;;    condrestart|try-restart)        rh_status_q || exit 0            ;;    *)        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"        exit 2esac

Then grant the execution permission to the script:

# chmod +x /etc/rc.d/init.d/nginx

Add it to the Service Management list and enable it to automatically start upon startup:

# chkconfig --add nginx# chkconfig nginx on

Then you can start the service and test it:

# service nginx start# vim /usr/html/index.html    

Instance

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/013632AQ-1.jpg "style =" float: none; "title =" n1.jpg "/>

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/0136324534-2.jpg "style =" float: none; "title =" n2.jpg "/>

3. Install keepalive

Installation plan: the high-availability Mobile IP address is 172.16.12.254

1. Install software

Because keepalive already exists in rhel6.4, We will directly use yum to install it here. Please configure the yum source (keepalive dependency, if you cannot resolve the dependency on your own, use yum to install it)

# yum install keepalived -y

2. modify the configuration file

# cd /etc/keepalived/# vim keepalived.conf

! Configuration File for keepalivedglobal_defs {   notification_email {        root@localhost   }   notification_email_from root@localhost   smtp_server 127.0.0.1   smtp_connect_timeout 30   router_id LVS_DEVEL}vrrp_script chk_nginx {    script "killall -0 nginx"    interval 2    weight -2    fall 2    rise 1}vrrp_script chk_schedown {   script "[[ -f /etc/keepalived/down ]] && exit 1 || exit 0"   interval 2   weight -2}vrrp_instance VI_1 {    state MASTER    interface eth0    virtual_router_id 61    priority 101    advert_int 1    authentication {        auth_type PASS        auth_pass nginxpass    }    virtual_ipaddress {        172.16.12.254/16 dev eth0 label eth0:0    }    track_script {        chk_nginx        chk_schedown    }    notify_master "/etc/keepalived/notify.sh master"    notify_backup "/etc/keepalived/notify.sh backup"    notify_fault "/etc/keepalived/notify.sh fault"}

On the slave server, you only need to modify the following two items:

state BACKUPpriority 100

3. Provide a script to manually stop a node.

# Vim notify. sh # create a script

#!/bin/bash# Author: WangEJ <ywhwzhang@gmail.com># description: An example of notify script#ifalias=${2:-eth0:0}interface=$(echo $ifalias | awk -F: '{print $1}')vip=$(ip addr show $interface | grep $ifalias | awk '{print $2}')#contact='ywhwzhang@gmail.com'contact='root@localhost'workspace=$(dirname $0)notify() {    subject="$ip change to $1"    body="$ip change to $1 $(date '+%F %H:%M:%S')"    echo $body | mail -s "$1 transition" $contact}case "$1" in    master)        notify master        exit 0    ;;    backup)        notify backup        /etc/rc.d/init.d/nginx restart        exit 0    ;;    fault)        notify fault        exit 0    ;;    *)        echo 'Usage: $(basename $0) {master|backup|fault}'        exit 1    ;;esac

Add to the service list starting from startup:

# chkconfig keepalived on

Then you can start the service and test the service:

# service keepalived start

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/01363255c-3.jpg "style =" float: none; "title =" k1.jpg "/>

Next, we will manually close the master node and transfer the IP address to the slave node for testing:650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/0136321601-4.jpg "title =" k2.jpg "/>

At the same time, observe the IP status of the two nodes:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/0136324137-5.jpg "style =" float: none; "title =" ip1.jpg "/>

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/0136323618-6.jpg "style =" float: none; "title =" ip2.jpg "/>

Iv. Additional instructions

So far, we have built the nginx-based keepalive high-availability service. If you have any questions or any omissions in the article, please leave a message and let us discuss and make progress together!


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.