操作系统:centos-7
jdk:jdk8
第一步、准备文件
nginx-1.8.1-tar.gz 下载地址:http://nginx.org/en/download.html
tomcat-8.0.42.tar.gz 下载地址:http://tomcat.apache.org/
再准备一个测试工程,本例中测试工程名称为”TestNginx”
第二步、准备环境
1、安装nginx,步骤略。详细安装可参考我的另一篇nginx安装的文章.
2、安装tomcat,并将”TestNginx”工程拷备到webapps目录。为了实现负载,tomcat布署两台机器。
Nginx服务器ip:192.168.152.131:80
Tomcat服务器ip:192.168.152.132:8080、192.168.152.133:8080
注:tomcat服务器可以使用windows,只需要保证nginx服务器与tomcat服务器网络畅通即可。
第三步、修改nginx配置文件
找到nginx安装目录conf ginx.conf文件,修改如下内容:
#user nobody; worker_processes 1; #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #pid logs/nginx.pid; events { worker_connections 1024; } http { 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; #负载均衡列表 upstream TestNginx{ server 192.168.152.132:8080 weight=5; #weight数值越大,被分配到的机率越大 server 192.168.152.133:8080 weight=5; } sendfile on; #tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 65; #gzip on; server { listen 80; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; location / { root TestNginx; index index.html index.htm; proxy_pass http://TestNginx; #所有请求转到tomcat服务器 }
#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; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ .php$ { # proxy_pass http://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # #location ~ .php$ { # root html; # fastcgi_pass 127.0.0.1:9000; # fastcgi_index index.php; # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; # include fastcgi_params; #} # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ /.ht { # deny all; #} } # another virtual host using mix of IP-, name-, and port-based configuration # #server { # listen 8000; # listen somename:8080; # server_name somename alias another.alias; # location / { # root html; # index index.html index.htm; # } #} # HTTPS server # #server { # listen 443 ssl; # server_name localhost; # ssl_certificate cert.pem; # ssl_certificate_key cert.key; # ssl_session_cache shared:SSL:1m; # ssl_session_timeout 5m; # ssl_ciphers HIGH:!aNULL:!MD5; # ssl_prefer_server_ciphers on; # location / { # root html; # index index.html index.htm; # } #} } |
第四步、访问nginx服务器
在浏览器中输入nginx服务器地址,并不断刷新,可看到交替出现如下页面,即实现了nginx&tomcat负载均衡。
第五步、后续说明
通过上面的描述,可以看出nginx&tomcat负载均衡的关键点就是nginx.conf配置文件的修改。本例只是做一个快速上手的描述,以便建立学习信心。其他高级用法后续说明。