2018-12-06 基于apache-httpd实现微服务的请求代理

微服务化以后,每个模块都会运行自己的进程,使用自己的独立应用根路径。但在前端,不希望看见这些,而是希望通过一个统一的域名和端口,访问所有的服务。此时,最简单的方案,就是apache-httpd,或类似的代理方案。

  1. 首先,配置httpd启用代理。
    对于apache-httpd-2.4.*系列版本,安装时就已经配置好了代理服务相关的子模块了。可以通过检查 /etc/httpd/conf.module.d/00-proxy.conf 配置文件是否存在,以及其内容是否包含:
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so

来判断。

  1. 配置httpd的代理规则。
    在 /etc/httpd/conf.d 中,增加一个代理规则配置文件 proxy.conf:
vi /etc/httpd/conf.d/proxy.conf

填写如下内容:

ProxyPass /proxy_url http://ip:port/real_url
ProxyPassReverse /proxy_url http://ip:portreal_url

比如,我在主机 192.168.1.154 上,部属了三个微服务模块,其中:

  1. /security子模块,请求模式为 http://192.168.1.154:58002/security
  2. /humans子模块,请求模式为 http://192.168.1.154:58003/humans
  3. /finance子模块,请求模式为 http://192.168.1.154:58004/finance

那么,可以配置为:

ProxyPass /security http://192.168.1.154:58002/security
ProxyPassReverse /security http://192.168.1.154:58002/security
ProxyPass /humans http://192.168.1.154:58003/humans
ProxyPassReverse /humans http://192.168.1.154:58003/humans
ProxyPass /finance http://192.168.1.154:58004/finance
ProxyPassReverse /finance http://192.168.1.154:58004/finance

然后,重启httpd服务:

$ service httpd restart

然而,测试的时候,系统报 503 错误。
检查日志:

$ tail -100f /var/log/httpd/error.log

发现错误信息如下:

[proxy:error] [pid 13107:tid 140195550705408] (13)Permission denied: AH00957: HTTP: attempt to connect to 192.168.1.154:58003

猜测是selinux的权限控制导致的,经过百度,找到解决方案:

$ setsebool -P httpd_can_network_connect 1

再次访问,发现代理已经生效。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容