LoginSignup
32
22

More than 3 years have passed since last update.

nginxで同一ホスト内にリバースプロキシしようとするとエラーが出る

Last updated at Posted at 2017-06-04

nginxで同一ホスト内にリバースプロキシしようとするとエラーが出る

環境

  • Amazon EC2
  • AMI: Centos7
  • nginx/1.12.0 (80port)
  • puma (3000port)

状況

例えば、/etc/nginx/conf.d/default.confに以下のような設定をした時、

/etc/nginx/conf.d/default.conf
server {
    listen       80;
    server_name  localhost;

   location / {
    proxy_pass http://localhost:3000/;
    }
}

ブラウザで接続してもつながらない。3000ポート直打ちだとアクセスできる。また、なぜか別ホストに変えてみるとプロキシできる。  
curlでレスポンスを確認してみる。

$ curl -L -I xxx.com
HTTP/1.1 502 Bad Gateway
Server: nginx/1.12.0
Date: Thu, 01 Jun 2017 08:34:06 GMT
Content-Type: text/html
Content-Length: 537
Connection: keep-alive
ETag: "xxxxxxxxxx-xxx"

502が出ている。
また、nginxのログを確認すると、

/var/log/nginx/error.log
2017/06/01 08:38:16 [crit] 27144#27144: *1 connect() to 127.0.0.1:3000 failed (13: Permission denied) while connecting to upstream, client: xxx.xxx.xxx.xxx, server: localhost, request: "HEAD / HTTP/1.1", upstream: "http://127.0.0.1:3000/", host: xxx.com"
2017/06/01 08:38:16 [warn] 27144#27144: *1 upstream server temporarily disabled while connecting to upstream, client: xxx.xxx.xxx.xxx, server: localhost, request: "HEAD / HTTP/1.1", upstream: "http://127.0.0.1:3000/", host: "xxx.com"
2017/06/01 08:38:16 [crit] 27144#27144: *1 connect() to [::1]:3000 failed (13: Permission denied) while connecting to upstream, client: xxx.xxx.xxx.xxx, server: localhost, request: "HEAD / HTTP/1.1", upstream: "http://[::1]:3000/", host: "xxx.com"
2017/06/01 08:38:16 [warn] 27144#27144: *1 upstream server temporarily disabled while connecting to upstream, client: xxx.xxx.xxx.xxx, server: localhost, request: "HEAD / HTTP/1.1", upstream: "http://[::1]:3000/", host: "xxx.com"

どうやら権限の関係でうまくプロキシ出来ていないよう。しかしnginxの実行ユーザをrootにしてみても解消されない。

解決策

どうやらSELinuxが効いているせいらしい。 Centos7のAMIでは初期は無効だった気がするが有効になっていたみたい。

httpd_can_network_connectを許可してやることで接続できるようになるはず。

$ sudo setsebool httpd_can_network_connect on -P

確認してみます。

$ curl -L -I xxx.com
HTTP/1.1 200 OK
Server: nginx/1.12.0
Date: Thu, 01 Jun 2017 08:40:36 GMT
Content-Type: text/html; charset=utf-8
Connection: keep-alive
~~~~~~~~~~~~~~~~~~~~

接続できました。

結論

私はSELinuxを切って解決しました。

32
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
32
22