背景:
最近公司分配一个项目,做一个直播 APP 的后台,像这种随时都有用户在线的情况,后台一定不能 down 掉,而且只做一台服务器的话压力肯定很大,所以考虑用 nginx 做负载均衡
环境:
三台 linux 服务器,一台反向代理服务器,两台负载均衡服务器
反向代理服务器 10.10.10.30 80
负载均衡服务器 10.10.10.40 80
10.10.10.50 80
首先编译安装 nginx,安装编译环境:
yum install gcc-c++
yum -y install zlib zlib-devel openssl openssl--devel pcre pcre-devel
yum -y install openssl openssl—devel
安装编译环境可能遇到的问题:
要是这样编译的时候还是找不到 openssl 库,就需要下载 openssl 源文件, 解压后, 将路径指定到解压的路径
./configure --prefix=/usr/local/nginx --with-http_ssl_module--with-openssl=/usr/local/src/openssl-xxxx --with-pcre--with-http_stub_status_module
接下来编译安装 nginx
tar zxvf nginx-1.8.0.tar.gz
cd nginx-1.8.0
./configure
make
make install
配置完成后测试是否正常
/usr/local/nginx/sbin/nginx -t
接着启动 nginx
/usr/local/nginx/sbin/nginx
若修改后配置文件或者将配置文件覆盖修改的 ,需要执行:
/usr/local/nginx/sbin/nginx -s reload
nginx 主目录:/usr/local/nginx
nginx 主页目录:/usr/local/nginx/html
nginx 主配置文件目录:/usr/local/nginx/conf
启动成功之后,浏览器输入 http://10.10.10.30/ 可进入测试页面
负载均衡服务器配置:
- 1 upstream mynginx {
- 2
- 3 server 10.10.10.40:80 weight=10;
- 4 server 10.10.10.50:80 weight=10;
- 5
- 6 }
- 7
- 8 server {
- 9 listen 80;
- 10 server_name www.asen0713.com;
- 11
- 12 #charset koi8-r;
- 13
- 14 #access_log logs/host.access.log main;
- 15
- 16 location / {
- 17 root html;
- 18 proxy_pass http://mynginx;
- 19 }
- 20
- 21 #error_page 404 /404.html;
- 22
- 23 # redirect server error pages to the static page /50x.html
- 24 #
- 25 error_page 500 502 503 504 /50x.html;
- 26 location = /50x.html {
- 27 root html;
- 28 }
- 29
- 30 # proxy the PHP scripts to Apache listening on 127.0.0.1:80
- 31 #
- 32 #location ~ \.php$ {
- 33 # proxy_pass http://127.0.0.1;
- 34 #}
- 35
- 36 # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
- 37 #
- 38 #location ~ \.php$ {
- 39 # root html;
- 40 # fastcgi_pass 127.0.0.1:9000;
- 41 # fastcgi_index index.php;
- 42 # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
- 43 # include fastcgi_params;
- 44 #}
- 45
- 46 # deny access to .htaccess files, if Apache's document root
- 47 # concurs with nginx's one
- 48 #
- 49 #location ~ /\.ht {
- 50 # deny all;
- 51 #}
- 52}
配置好了之后重新加载配置文件:/usr/local/nginx/sbin/nginx -s reload,或者重启 nginx 负载均衡服务器,输入 www.asen0713.com 可看到负载均衡效果
注意事项:
1、修改 C:\Windows\System32\drivers\etc 下的 hosts 文件加入 10.10.10.30 www.asen0713.com 一行
2、火狐和 IE 需要按 ctrl+F5 强制刷新才能看到效果,而谷歌浏览器刚好相反
这样负载均衡就已经配置完了,如果 10.10.10.40 80 10.10.10.50 80 其中一台 down 掉,负载均衡服务器会自动分配到另外一台,服务正常访问
常用命令:
启动:/usr/local/nginx/sbin/nginx
以配置文件启动:/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
重新加载配置文件:/usr/local/nginx/sbin/nginx -s reload
停止:/usr/local/nginx/sbin/nginx -s stop
遗留问题:
1、如果负载均衡服务器 down 掉,将无法访问
2、配置负载均衡服务器,session 也会随之分配到对应服务器,这样 session 将不能共享,获取资源出现问题
3、文件上传下载也会被分配到不同服务器
来源: http://www.cnblogs.com/asen0713/p/6747892.html