我在“swarm.example.com”上运行 docker swarm。服务器上有一个容器正在运行,可以通过“swarm.example.com:3000”访问。
在服务器“example.com”上,我运行了一个 nginx 反向代理,规则如下
server {
listen 80;
server_name app.example.com;
location / {
proxy_pass http://swarm.example.com:3000;
}
}
当我尝试访问 app.example.com 时502 网关故障错误。我遗漏了什么吗?
所有服务器均运行 CentOS 7.6
谢谢!
答案1
尝试通过反向代理访问后端会导致 502 Bad Gateway 错误:
$ wget -S --spider http://nginxtest.example.com/
Spider mode enabled. Check if remote file exists.
--2019-05-18 10:12:11-- http://nginxtest.example.com/
Resolving nginxtest.example.com (nginxtest.example.com)... 192.168.15.20
Connecting to nginxtest.example.com (nginxtest.example.com)|192.168.15.20|:80... connected.
HTTP request sent, awaiting response...
HTTP/1.1 502 Bad Gateway
Server: nginx/1.12.2
Date: Sat, 18 May 2019 08:12:11 GMT
Content-Type: text/html
Content-Length: 3693
Connection: keep-alive
ETag: "5a9e5ebd-e6d"
Remote file does not exist -- broken link!!!
这很可能是因为 selinux 默认不允许网络服务器进行传出连接,因为这通常是它们不做的事情。
您将在 /var/log/nginx/error.log 中找到类似这样的条目:
2019/05/18 10:12:11 [crit] 1041#0: *5 connect() 至 192.168.15.52:3000 失败(13:权限被拒绝)连接到上游,客户端:146.140.37.47,服务器:_,请求:“HEAD / HTTP/1.1”,上游:“http://192.168.15.52:3000/", 主机: "nginxtest.example.com"
此外,您还会在 /var/log/audit/audit.log 中找到如下条目:
类型 = AVC 消息 = 审核(1558167131.910:463):avc:拒绝 pid = 1041 的 { name_connect } comm =“nginx”dest = 3000 scontext = system_u:system_r:httpd_t:s0 tcontext = system_u:object_r:ntop_port_t:s0 tclass = tcp_socket permissive = 0 类型 = SYSCALL 消息 = 审核(1558167131.910:463):arch = c000003e syscall = 42 成功 = 否退出 = -13 a0 = 8 a1 = 562671c4eef0 a2 = 10 a3 = 7ffcfbc72530 项目 = 0 ppid = 1006 pid = 1041 auid = 4294967295 uid = 996 gid=994 euid=996 suid=996 fsuid=996 egid=994 sgid=994 fsgid=994 tty=(无) ses=4294967295 comm="nginx" exe="/usr/sbin/nginx" subj=system_u:system_r:httpd_t:s0 key=(空)
运行以下命令允许nginx连接到其他主机:
setsebool -P httpd_can_network_connect true
(该参数-p
使设置持久化。否则下次重启后它将被重置。)
现在代理就可以工作了:
$ wget -S --spider http://nginxtest.example.com/
Spider mode enabled. Check if remote file exists.
--2019-05-18 10:15:14-- http://nginxtest.example.com/
Resolving nginxtest.example.com (nginxtest.example.com)... 192.168.15.20
Connecting to nginxtest.example.com (nginxtest.example.com)|192.168.15.20|:80... connected.
HTTP request sent, awaiting response...
HTTP/1.1 200 OK
Server: nginx/1.12.2
Date: Sat, 18 May 2019 08:15:15 GMT
Content-Type: text/html
Content-Length: 40
Connection: keep-alive
Last-Modified: Sat, 18 May 2019 08:08:16 GMT
ETag: "5cdfbd70-28"
Accept-Ranges: bytes
Length: 40 [text/html]
Remote file exists and could contain further links,
but recursion is disabled -- not retrieving.
如果你想了解更多,这里有一个非常详细的nginx 网站上有关 nginx 和 selinux 的文章。