LoginSignup
11
9

More than 5 years have passed since last update.

h2oとUnixドメインソケット

Last updated at Posted at 2014-12-10

h2oは部分的にではありますが、Unixドメインソケットをサポートしています。

Unixドメインソケットでlisten

h2oでUnixドメインソケットでlistenするには例えば以下のようなconfを用意します。

h2o.conf
listen:
  port: /tmp/h2o.sock
  type: unix
hosts:
  default:
    paths:
      /:
        file.dir: examples/doc_root
    access-log: /dev/stdout

この設定で起動しましょう。

$ make h2o && ./h2o -c h2o.conf

また/tmp/h2o.sockにアクセスするプログラムを用意します。ここではPHPで書いていますが、Unixドメインソケットを扱えるならなんでもいいです。

connect_h2o.php
<?php

$sock = fsockopen("unix:///tmp/h2o.sock", 0);

fwrite($sock, "GET / HTTP/1.1
Host: 127.0.0.1
Connection: Close

");

while (!feof($sock)) {
    echo fgets($sock);
}

fclose($sock);

connect_h2o.phpを実行してみます。

$ php connect_h2o.php
HTTP/1.1 200 OK
date: Tue, 09 Dec 2014 23:38:04 GMT
server: h2o/0.1
connection: close
content-length: 180
content-type: text/html
last-modified: Sun, 09 Nov 2014 20:07:25 GMT
etag: "545fc97d-b4"

<!DOCTYPE html>
<html>
  <header>
    <title>Welcome to H2O</title>
  </header>
  <body>
    <p>Welcome to H2O - an optimized HTTP server</p>
    <p>It works!</p>
  <body>
</html>
$

ちゃんとレスポンスが返ってきました。

Unixドメインソケットへリバースプロキシ

まだmasterにマージされていませんが、Unixドメインソケットにリバースプロキシを行えるようにするためのブランチとPRがあります。(時間取れてなくて絶賛放置中です。自分から送っておいてすいません to @kazuho )

試しにこのPRのブランチをcheckoutします。

$ git remote add cubicdaiya https://github.com/cubicdaiya/h2o.git
$ git fetch cubicdaiya
$ git checkout cubicdaiya/feature/revproxy-unix

設定はこんな感じになります。(多分masterにマージされる時には別の書式になると思います)

h2o.conf
listen:
  port: 8081
hosts:
  default:
    paths:
      /tcp:
        proxy.reverse.url: http://127.0.0.1/
      /unix:
        proxy.reverse.path: unix:/tmp/nginx.sock:/

プロキシ先はnginxなのでnginx.confも用意します。

nginx.conf
worker_processes 1;

events {
    worker_connections 1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    keepalive_timeout  65;

    server {
        listen 80;
        root   html;
    }

    server {
        listen unix:/tmp/nginx.sock;
        root   html;
    }

}

手元(MacBook Pro)でh2oとnginx両方を起動した状態でh2oにabによるベンチを実行した結果が以下になります。

$ ab -k -n 10000 -c 500 "http://127.0.0.1:8081/tcp" 2>&1 | grep "Requests per second:"
Requests per second:    8818.33 [#/sec] (mean)
$ ab -k -n 10000 -c 500 "http://127.0.0.1:8081/unix" 2>&1 | grep "Requests per second:"       
Requests per second:    17492.24 [#/sec] (mean)
$

というわけで大体2倍くらいのパフォーマンスが出ました。

11
9
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
11
9