技术交流QQ群:①185473046   ②190706903   ③203744115   网站地图
登录

下次自动登录
现在的位置: 首页LNMP>正文
Nginx负载均衡服务器配置教程
2012年05月09日 LNMP 评论数 9 ⁄ 被围观 31,206次+


说明:
Nginx负载均衡服务器:
系统:CentOS 5.5
IP:192.168.21.164
Web服务器列表:
Web1:192.168.21.160
Web2:192.168.21.169
实现目的:
用户访问192.168.21.164服务器时,通过Nginx负载均衡到Web1和Web2服务器
下面配置Nginx负载均衡服务器
准备篇:
一、配置好IP、DNS 、网关,确保使用远程连接工具能够连接服务器
二、配置防火墙,开启80端口
系统运维 www.osyunwei.com 温馨提醒:qihang01原创内容©版权所有,转载请注明出处及原文链接
vi /etc/sysconfig/iptables   #编辑防火墙配置文件,添加以下内容
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT
特别提示:很多网友把这两条规则添加到防火墙配置的最后一行,导致防火墙启动失败,正确的应该是添加到默认的22端口这条规则的下面
添加好之后防火墙规则如下所示:
#####################################################################
# Firewall configuration written by system-config-securitylevel
# Manual customization of this file is not recommended.
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:RH-Firewall-1-INPUT - [0:0]
-A INPUT -j RH-Firewall-1-INPUT
-A FORWARD -j RH-Firewall-1-INPUT
-A RH-Firewall-1-INPUT -i lo -j ACCEPT
-A RH-Firewall-1-INPUT -p icmp --icmp-type any -j ACCEPT
-A RH-Firewall-1-INPUT -p 50 -j ACCEPT
-A RH-Firewall-1-INPUT -p 51 -j ACCEPT
-A RH-Firewall-1-INPUT -p udp --dport 5353 -d 224.0.0.251 -j ACCEPT
-A RH-Firewall-1-INPUT -p udp -m udp --dport 631 -j ACCEPT
-A RH-Firewall-1-INPUT -p tcp -m tcp --dport 631 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT
-A RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibited
COMMIT
#####################################################################
/etc/init.d/iptables restart #最后重启防火墙使配置生效
三、关闭SELINUX
vi /etc/selinux/config   #编辑配置文件
#SELINUX=enforcing #注释掉
#SELINUXTYPE=targeted #注释掉
SELINUX=disabled #增加
:wq #保存
shutdown -r now #重启系统
四 、系统约定
软件源代码包存放位置:/usr/local/src
源码包编译安装位置:/usr/local/软件名字
五、下载软件包
1、下载nginx(目前稳定版)
http://nginx.org/download/nginx-1.0.15.tar.gz
2、下载pcre (支持nginx伪静态)
ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.30.tar.gz
3、下载ngx_cache_purge(清除指定URL缓存,方便以后扩展配置nginx缓存服务器)
http://labs.frickle.com/files/ngx_cache_purge-1.5.tar.gz
六、安装编译工具及库文件(使用CentOS yum命令安装,安装的包比较多,方便以后配置lnmp环境)
yum install make apr* autoconf automake curl curl-devel gcc gcc-c++ zlib-devel openssl openssl-devel pcre-devel gd kernel keyutils patch perl kernel-headers compat*  cpp glibc libgomp libstdc++-devel keyutils-libs-devel libsepol-devel libselinux-devel krb5-devel zlib-devel libXpm* freetype libjpeg* libpng* php-common php-gd ncurses* libtool* libxml2 libxml2-devel patch
安装篇
以下是用putty工具远程登录到服务器,在命令行下面操作的
安装pcre
cd /usr/local/src
mkdir /usr/local/pcre #创建安装目录
tar zxvf pcre-8.30.tar.gz
cd pcre-8.30
./configure --prefix=/usr/local/pcre #配置
make
make install
安装 nginx
groupadd  www  #添加www组
useradd -g www www -s /bin/false  #创建nginx运行账户www并加入到www组,不允许www用户直接登录系统cd /usr/local/src  #进入安装目录
tar  zxvf  ngx_cache_purge-1.5.tar.gz  #解压
tar  zxvf nginx-1.0.15.tar.gz  #解压
cd nginx-1.0.15
./configure --prefix=/usr/local/nginx --without-http_memcached_module
--user=www --group=www --with-http_stub_status_module --with-openssl=/usr/ --with-pcre=/usr/local/src/pcre-8.30  --add-module=../ngx_cache_purge-1.5  #配置
注意:--with-pcre=/usr/local/src/pcre-8.30指向的是源码包解压的路径,而不是安装的路径,否则会报错
make  #编译
make install #安装
/usr/local/nginx/sbin/nginx  #启动Nginx
=======================================================
设置nginx开启启动
vi /etc/rc.d/init.d/nginx    #编辑启动文件添加下面内容
#!/bin/bash
# nginx Startup script for the Nginx HTTP Server
# it is v.0.0.2 version.
# chkconfig: - 85 15
# description: Nginx is a high-performance web and proxy server.
#              It has a lot of features, but it's not for everyone.
# processname: nginx
# pidfile: /var/run/nginx.pid
# config: /usr/local/nginx/conf/nginx.conf
nginxd=/usr/local/nginx/sbin/nginx
nginx_config=/usr/local/nginx/conf/nginx.conf
nginx_pid=/usr/local/nginx/logs/nginx.pid
RETVAL=0
prog="nginx"
# Source function library.
.  /etc/rc.d/init.d/functions
# Source networking configuration.
.  /etc/sysconfig/network
# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 0
[ -x $nginxd ] || exit 0
# Start nginx daemons functions.
start() {
if [ -e $nginx_pid ];then
echo "nginx already running...."
exit 1
fi
echo -n $"Starting $prog: "
daemon $nginxd -c ${nginx_config}
RETVAL=$?
echo
[ $RETVAL = 0 ] && touch /var/lock/subsys/nginx
return $RETVAL
}
# Stop nginx daemons functions.
stop() {
echo -n $"Stopping $prog: "
killproc $nginxd
RETVAL=$?
echo
[ $RETVAL = 0 ] && rm -f /var/lock/subsys/nginx /usr/local/nginx/logs/nginx.pid
}
reload() {
echo -n $"Reloading $prog: "
#kill -HUP `cat ${nginx_pid}`
killproc $nginxd -HUP
RETVAL=$?
echo
}
# See how we were called.
case "$1" in
start)
start
;;
stop)
stop
;;
reload)
reload
;;
restart)
stop
start
;;

status)
status $prog
RETVAL=$?
;;
*)
echo $"Usage: $prog {start|stop|restart|reload|status|help}"
exit 1
esac
exit $RETVAL
=======================================================
:wq! #保存退出
chmod 775 /etc/rc.d/init.d/nginx  #赋予文件执行权限
chkconfig nginx on    #设置开机启动
/etc/rc.d/init.d/nginx restart #重启Nginx
=======================================================
配置篇
配置Nginx
cp /usr/local/nginx/conf/nginx.conf  /usr/local/nginx/conf/nginx.confbak  #备份nginx配置文件
(一)、设置nginx运行账号
vi /usr/local/nginx/conf/nginx.conf   #编辑
找到user nobody;修改为
user www www;    #在第一行
(二)、禁止nginx空主机头
vi /usr/local/nginx/conf/nginx.conf   #编辑
找到server,在上面一行添加如下内容:
##############################
server {
listen       80 default;
server_name  _;
location / {
root   html;
return 404;
}
location ~ /.ht {
deny  all;
}
}
##############################
/etc/rc.d/init.d/nginx restart     #重启nginx
这样设置之后,空主机头访问会直接跳转到nginx404错误页面。
(三)、添加nginx虚拟主机包含文件
cd /usr/local/nginx/conf/   #进入nginx安装目录
mkdir vhost   #建立虚拟目录
vi  /usr/local/nginx/conf/nginx.conf   #编辑
找到上一步添加的代码,在最后添加如下内容:
include  vhost/*.conf;
例如:
##############################
server {
listen       80 default;
server_name  _;
location / {
root   html;
return 404;
}
location ~ /.ht {
deny  all;
}
}
include  vhost/*.conf;
##############################
(四)、添加Web服务器列表文件
cd  /usr/local/nginx/conf/   #进入目录
touch  mysvrhost.conf  #建立文件
vi  /usr/local/nginx/conf/nginx.conf   #编辑
找到上一步添加的代码,在下面添加一行
include  mysvrhost.conf;
系统运维 www.osyunwei.com 温馨提醒:qihang01原创内容©版权所有,转载请注明出处及原文链接
(五)、设置nginx全局参数
vi  /usr/local/nginx/conf/nginx.conf   #编辑 
worker_processes 2;       # 工作进程数,为CPU的核心数或者两倍
events
{
use epoll;   #增加
worker_connections 65535;    #修改为65535,最大连接数。
}
#############以下代码在http { 部分增加与修改##############
server_names_hash_bucket_size 128;   #增加
client_header_buffer_size 32k;       #增加
large_client_header_buffers 4 32k;   #增加
client_max_body_size 300m;           #增加
tcp_nopush     on;      #修改为on
keepalive_timeout  60;  #修改为60
tcp_nodelay on;        #增加
server_tokens off;     #增加,不显示nginx版本信息
gzip  on;  #修改为on
gzip_min_length  1k;      #增加
gzip_buffers     4 16k;   #增加
gzip_http_version 1.1;    #增加
gzip_comp_level 2;        #增加
gzip_types       text/plain application/x-javascript text/css application/xml;  #增加
gzip_vary on;  #增加
(六)、设置Web服务器列表
cd  /usr/local/nginx/conf/   #进入目录
vi mysvrhost.conf  #编辑,添加以下代码
upstream  osyunweihost {
server 192.168.21.160:80 weight=1 max_fails=2 fail_timeout=30s;
server 192.168.21.169:80 weight=1 max_fails=2 fail_timeout=30s;
ip_hash;
}
(七)、新建虚拟主机配置文件
cd /usr/local/nginx/conf/vhost   #进入虚拟主机目录
touch osyunwei.conf #建立虚拟主机配置文件
vi  osyunwei.conf #编辑
server
{
listen       80;
server_name  www.osyunwei.com bbs.osyunwei.com sns.osyunwei.com;
location /
{
proxy_next_upstream http_502 http_504 error timeout invalid_header;
proxy_pass http://osyunweihost;
#proxy_redirect off;
proxy_set_header Host  $host;
proxy_set_header X-Forwarded-For  $remote_addr;
}
log_format  access  '$remote_addr - $remote_user [$time_local] $request '
'"$status" $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log  /usr/local/nginx/logs/access.log  access;

location /NginxStatus {
stub_status on;
access_log  on;
auth_basic  "NginxStatus";
#auth_basic_user_file  pwd;
}

}
:wq!  #保存配置
service nginx restart  #重启nginx
测试篇
域名:
www.osyunwei.com
bbs.osyunwei.com
sns.osyunwei.com
分别解析到192.168.21.164
客户访问这三个站点的时候,Nginx根据客户访问的ip_hash值,负载均衡到Web1和Web2服务器上

至此,Nginx负载均衡服务器配置教程完成
系统运维 www.osyunwei.com 温馨提醒:qihang01原创内容©版权所有,转载请注明出处及原文链接
附:相关配置文件

1、/usr/local/nginx/conf/nginx.conf


user  www www;
worker_processes  2;
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
#pid        logs/nginx.pid;

events {
use epoll;
worker_connections  65535;
}

http {
include   mysvrhost.conf;
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;

server_names_hash_bucket_size 128;
client_header_buffer_size 32k;
large_client_header_buffers 4 32k;
client_max_body_size 300m;
sendfile        on;
tcp_nopush     on;

#keepalive_timeout  0;
keepalive_timeout  60;
tcp_nodelay on;
server_tokens off;
gzip  on;
gzip_min_length  1k;
gzip_buffers     4 16k;
gzip_http_version 1.1;
gzip_comp_level 2;
gzip_types       text/plain application/x-javascript text/css application/xml;
gzip_vary on;

server {
listen       80 default;
server_name  _;
location / {
root   html;
return 404;
}
location ~ /.ht {
deny  all;
}
}
include  vhost/*.conf;
}

2、/usr/local/nginx/conf/mysvrhost.conf


upstream  osyunweihost {
server 192.168.21.160:80 weight=1 max_fails=2 fail_timeout=30s;
server 192.168.21.169:80 weight=1 max_fails=2 fail_timeout=30s;
ip_hash;
}

3、/usr/local/nginx/conf/vhost/osyunwei.conf


server
{
listen       80;
server_name  bbs.osyunwei.com sns.osyunwei.com;
location /
{
proxy_next_upstream http_502 http_504 error timeout invalid_header;
proxy_pass http://osyunweihost;
     #proxy_redirect off;
proxy_set_header Host  $host;
proxy_set_header X-Forwarded-For  $remote_addr;
}
log_format  access  '$remote_addr - $remote_user [$time_local] $request '
'"$status" $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log  /usr/local/nginx/logs/access.log  access;

location /NginxStatus {
stub_status on;
access_log  on;
auth_basic  "NginxStatus";
#auth_basic_user_file  pwd;
}

}
     

  系统运维技术交流QQ群:①185473046 系统运维技术交流□Ⅰ ②190706903 系统运维技术交流™Ⅱ ③203744115 系统运维技术交流™Ⅲ

目前有 9 条留言 其中:访客:9 条, 博主:0 条

  1. 感恩的心 : 2012年05月16日00:31:09  1楼

    你的文章写的好详细,非常用心,真的非常感谢分享!可以帮助到更多需要帮助的人!

  2. scott : 2012年06月11日11:48:07  2楼

    这篇文章还真不错,谢谢提供分享

  3. Ray : 2012年06月26日22:26:06  3楼

    请问下楼主,您分析的是nginx负载均衡的服务器,请问下那两个负载均衡的web服务器要如何配置,还是有点含糊,我实验了一个项目,就是负载过去web服务器提示404错误,麻烦您指导下,谢谢

  4. jied : 2012年07月10日15:49:04  4楼

    楼主辛苦了,想问一下楼主,架设好后显示的乱码 这个在哪里修改呢?

  5. suny2008 : 2012年08月28日21:38:39  5楼

    好,收藏学习了

  6. 35470345@qq.com : 2012年11月01日14:36:50  6楼

    非常感谢。

  7. Kanespartacus : 2013年09月09日14:25:43  7楼

    感谢分享!!!!

  8. 297189845@qq.com : 2014年01月21日09:49:24  8楼

    正在学习nginx,谢谢哦哦。

给我留言

您必须 [ 登录 ] 才能发表留言!



Copyright© 2011-2024 系统运维 All rights reserved
版权声明:本站所有文章均为作者原创内容,如需转载,请注明出处及原文链接
陕ICP备11001040号-3