Dockerには複数のコンテナ間の通信をサポートするための仕組みが用意されています。
これを試して見るため、lua-nginx-module で利用できるStorage(memcache, MySQL, redis)向けのアダプタを試す - Qiitaのredisのサンプルをdockerで構築してみました。
以下の2つのコンテナを作成してnginxのコンテナからredisのコンテナに接続します。
- nginx + nginx-lua-module + lua-resty-redis
- redis
cd ${docker-nginx-luaの作業ディレクトリ}
docker build -t hnakamur/nginx-lua .
cd ${docker-redisの作業ディレクトリ}
docker build -t hnakamur/redis .
コンテナの起動
docker run -d -p 6379:6379 -name redis hnakamur/redis
docker run -d -p 80:80 -link redis:redis hnakamur/nginx-lua
-link
の引数はコンテナ名:エイリアスという形式なんですが、エイリアスはコンテナ名と同じでも大丈夫でした。
この引数を指定することによりhnakmaur/nginx-luaのコンテナにはエイリアス名と公開ポートに対応してREDIS_PORT_6379_TCP_ADDR、REDIS_PORT_6379_TCP_PORTなどの環境変数が設定されます。
設定される環境変数はLink Containers - Docker Documentationに記載されています。
そこでnginxからredisに接続する処理では、これらの環境変数の値を使用します。
location /get {
content_by_lua '
local redis = require "resty.redis"
local client = redis:new()
client:connect(os.getenv("REDIS_PORT_6379_TCP_ADDR"), tonumber(os.getenv("REDIS_PORT_6379_TCP_PORT")))
local args = ngx.req.get_uri_args()
local key, field = args.key, args.field
local result, err = client:hmget(key, field)
ngx.say(result)
';
}
location /set {
content_by_lua '
local redis = require "resty.redis"
local client = redis:new()
client:connect(os.getenv("REDIS_PORT_6379_TCP_ADDR"), tonumber(os.getenv("REDIS_PORT_6379_TCP_PORT")))
local args = ngx.req.get_uri_args()
local key, field, val = args.key, args.field, args.value
client:hmset(key, field, val)
ngx.say("Saved!")
';
}
Core functionalityによると、nginxではデフォルトではTZ以外の全ての環境変数を削除するそうです。
そこで以下の設定をnginx.confに加えています。
env REDIS_PORT_6379_TCP_ADDR;
env REDIS_PORT_6379_TCP_PORT;
動作確認
OSXでは以下のポートフォワーディングを設定しています。
VBoxManage controlvm "boot2docker-vm" natpf1 "nginx,tcp,127.0.0.1,8080,,80"
そこで
curl 'http://localhost:8080/set?key=foo&filed=bar&value=baz'
で値を設定し、
curl 'http://localhost:8080/get?key=foo&filed=bar'
で値を取得できることを確認しました。