1、需求
假设需求:
有一台服务器部署了Nginx,ip为192.168.200.139:80,本地网关服务192.168.200.1:88,本地后台系统服务192.168.200.1:11000,需求为本地请求192.168.200.139:80,有Nginx代理到网关服务192.168.200.1:88,网关服务负载均衡到后台系统服务192.168.200.1:11000。
2、Nginx配置
2.1创建一个config文件
/etc/nginx/conf.d/创建my.conf
server {
listen 80;
server_name 名称;
#charset koi8-r;
#access_log /var/log/nginx/log/host.access.log main;
location / {
proxy_pass http://myName;
proxy_set_header Host $host;
}
#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 /usr/share/nginx/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;
#}
}
- listen: 监听Nginx所在服务器的80端口
- server_name: 给转发服务起一个名字
- location /: 当前监听的服务下所有路径都会转发到此处里的配置
- proxy_pass:要转发的地址,http://myName中的myName见下面配置
- proxy_set_header Host:设置转发时的请求头中的host,$host为原请求中的host
2.2配置Nginx的nginx.conf配置文件
在Nginx的nginx.conf文件中配置:
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/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 /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
upstream myName{
server 192.168.200.1:88;
}
include /etc/nginx/conf.d/*.conf;
}
- upstream myName:此处就是my.conf中proxy_pass要转发的地址,可配多个集群服务,Nginx负载均衡。
- include /etc/nginx/conf.d/*.conf:当前nginx.conf会引入 /etc/nginx/conf.d/文件夹下所有后缀为.conf的配置文件,所有我们上面自己创建的my.conf要放在/etc/nginx/conf.d/文件夹下
此时我们本地访问Nginx所在服务器192.168.200.139:80,会被Nginx负载均衡自动转发到upstream myName下配置的192.168.200.1:88网关上面。
3、SpringCloudGeteway网关配置
在网关的yml配置文件中配置:
spring:
cloud:
gateway:
routes:
# 本地host路由
- id: myName_host_route
uri: lb://mySystem # lib:负载均衡转发到mySystem服务
predicates:
- Host=192.168.200.139:80
- id:该路由名称
- uri:负载均衡到mySystem服务,该服务地址为:192.168.200.1:11000,注意mySystem服务一定要配置到注册中心中,参考nacos配置注册中心和配置中心
- predicates:断言,做条件判断
- Host=192.168.200.139:80:断言条件是所有的host为192.168.200.139:80的请求,都会被负载均衡到mySystem 所在服务中(192.168.200.1:11000)
到此,网关路由配置结束
测试本地请求192.168.200.139:80最终转发到192.168.200.1:11000服务中。
Nginx配置微服务转发: