前提:因为本次需要两个软件在本机不同端口提供http服务,于是我准备一个tomcat在8080端口,另一个nodejs程序在3000端口,前者自不用提,后者可以 去下载并安装配置Node.js启动。
nginx主要通过proxy_pass来配置反向代理,upstream模块实现负载均衡。我们简单修改C:\nginx-1.16.1\conf\nginx.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; sendfile on; #tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 65; #gzip on; upstream firstdemo{ server 127.0.0.1:8080; server 127.0.0.1:3000; } server { listen 80; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; location / { # root html; # index index.html index.htm; proxy_pass http://firstdemo; } #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; # } #} }
上面粗红体表示代理到firstdemo上。
粗蓝体则表示由8080和3000的端口分别对localhost:80的请求提供http服务。
之后使用C:\nginx-1.16.1>nginx.exe -s reload 重启nginx服务,在浏览器里输入localhost,再不断刷新,就可以轮换看到以下画面了:
这样每次刷新就会访问不同的服务器,至此我们实现了一个简单的负载均衡。
只启动一个比如3000的node server,不断刷新浏览器,然后再启动一个比如8080的tomcat,效果是什么样的诸位看官可以自行尝试一下。
--END-- 2019年12月14日06:37:45