理科系の勉強日記

Linux/Ubuntu/Mac/Emacs/Computer vision/Robotics

Lighttpdとnginxでリバースプロキシ

ゴール

フロントのサーバのIPアドレスが192.168.3.3で、127.0.0.1:8123で待っているflaskのweb APIをリバースプロキシで呼び出したい、という状況です。 Lighttpdとnginxどちらでもいいですが、設定が簡単で開発の盛んなnginxのほうがいいかもですね。 フロントのサーバはhttpsにしないといけませんが、それは後でやります。

index.html

hello world!

Flask

import flask

app = flask.Flask(__name__)

@app.route("/API_1", methods=["GET"])
def API_1():
    response = {}
    response["message"] = "Response from flask server[API_1]"
    return flask.jsonify(response)

@app.route("/API_2", methods=["GET"])
def API_2():
    response = {}
    response["message"] = "Response from flask server[API_2]"
    return flask.jsonify(response)

if __name__ == "__main__":
    app.run(debug=True, host="127.0.0.1", port=8123)

Lighttpd

server.modules   += ( "mod_proxy")

var.server_root = "/usr/local/var/www"
server.document-root = server_root
server.port = 8111
index-file.names += ("index.html")

$SERVER["socket"] == ":8111"{
  $HTTP["host"] == "192.168.3.3" {
    $HTTP["url"] =~ "^/API_1"{
    proxy.server = (
      "" => ((
      "host" => "127.0.0.1", 
      "port" => 8123
     ))     
     )
  }
 }
}

$SERVER["socket"] == ":8111"{
  $HTTP["host"] == "192.168.3.3" {
    $HTTP["url"] =~ "^/API_2"{
    proxy.server = (
      "" => ((
      "host" => "127.0.0.1", 
      "port" => 8123
     ))
    )
  }
 }
}

NGINX

http {
    server {
        listen       8111;
        server_name  192.168.3.3;

        # reverse proxy
        location /API_1 {
            proxy_pass http://127.0.0.1:8123;
            proxy_set_header Host $host;
        }

        location /API_2 {
            proxy_pass http://127.0.0.1:8123;
            proxy_set_header Host $host;
        }

        location / {
            root   html;
            index  index.html index.htm;
        }
    }
}

確認

どちらでも、192.168.3.3:8111から127.0.0.1:8123へアクセスできました。

    curl http://192.168.3.3:8111/API_1 -X GET
    > {
    > "message": "Response from flask server[API_1]"
    > }

    curl http://192.168.3.3:8111/API_2 -X GET
    > {
    > "message": "Response from flask server[API_2]"
    > }

    curl http://192.168.3.3:8111 -X GET
    > hello world!

メモ

Lighttpdは-Dでフォアグラウンド実行

$ lighttpd -f /usr/local/etc/lighttpd/lighttpd.conf -D

nginxは設定ファイルに以下のように書くとフォアグラウンド実行となります。

deamon off