1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Nginxを触る②

1
Posted at

はじめに

Nginxをリバースプロキシとして設定し、Node.jsアプリにリクエストを転送する構成を試しました。
が、proxy設定を書いたのにまったく反映されない問題にハマりました。
原因は、設定ファイルに書かれていたサーバー情報のバッティングでした。

やりたかったこと

[ブラウザ] → [Nginx:8080] → [Node.js:3000]

nginxを中間地点として、バックエンドのNode.jsにリクエスト送りたかった。

proxy用の設定ファイル

cat > /opt/homebrew/etc/nginx/servers/nodejs-proxy.conf << 'EOF'
server {
    listen 8080;
    location / {
        proxy_pass http://localhost:3000;
    }
}
EOF

問題:proxy_pass が効かない

この設定で curl http://localhost:8080 を叩いても、

👉 Node.jsではなく、静的なHTMLが返る

原因:nginx.conf の server が優先されていた

nodejs-proxy.conf とは別に、nginx.conf に設定していたserver 設定が使われていました。

server {
    listen 8080;
    root /opt/homebrew/var/www;
    index index.html;
}
  • メイン設定ファイルとリバースプロキシ用の設定ファイルで、サーバーlisten 8080 が被っていた
  • Nginxは最初にマッチしたserverを使う
  • 結果、nginx.conf 側の設定が使われる
  • nodejs-proxy.conf は無視される
    ということでした。

解決方法

nginx.conf の server を無効化

# server {
#     listen 8080;
#     root /opt/homebrew/var/

確認コマンド

nginx -t #文法チェック
nginx -T #サーバー確認

おわりに

今回リバースプロキシがうまくいかなかったのは、設定コードが間違ってるんじゃなくて被っているからでした。
Nginxで思い通りに動かない時は、今どのサーバーを使っているのか?同じパートのサーバーはないか?を疑おうと思います。

1
0
1

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?