8
12

More than 5 years have passed since last update.

DockerでRails+UnicornをUnixDomainSocketで動かす

Last updated at Posted at 2016-01-27

はじめに

構成

DockerのVOLUME機能を利用する。
Rails動作用コンテナでUnicornを起動して、ソケットがあるディレクトリにVOLUMEを作成する。
Nginx用コンテナ起動時に作成したVOLUMEを付けることで、Ngnixからソケットにアクセスできるようにする。

Railsアプリの作成

$ rails new blog --skip-bundle
$ vi blog/Gemfile
source 'https://rubygems.org'
gem 'rails', '4.2.5'
gem 'sqlite3'
gem 'unicorn'
conifg/unicorn.rb
rails_root = File.expand_path(".")
worker_processes 2
working_directory rails_root
timeout 15
preload_app true
listen "#{rails_root}/tmp/sockets/unicorn.sock", :backlog => 1024

Dockerfile

rails/Dockerfile
FROM ruby

VOLUME /var/www/blog/tmp/sockets

WORKDIR /var/www
COPY ./blog blog
WORKDIR /var/www/blog
RUN bundle config build.nokogiri --use-system-libraries
RUN bundle install
RUN bin/rake db:create
RUN bin/rake db:migrate

ENTRYPOINT ["bundle", "exec", "unicorn_rails", "-D", "-c", "config/unicorn.rb"]
nginx/Dockerfile
FROM nginx

COPY default.conf /etc/nginx/conf.d/default.conf
default.conf
upstream backend {
  server unix:/var/www/blog/tmp/sockets/unicorn.sock;
}

server {
  listen 80;
  server_name localhost;

  location / {
    if (-f $request_filename) { break; }
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://backend;
  }

  location @empty {
    empty_gif;
  }
}

Dockerイメージ作成

$ docker build -t rails/base ./rails
$ docker build -t nginx/rails ./nginx

Dockerコンテナ起動

$ docker run -d --name rails rails/base
$ docker run -d -p 80:80 --volumes-from rails nginx/rails

おわりに

NginxとRailsを同一サーバで動かす場合には、DockerのVOLUME機能を使用することで、ソケットへのアクセスが容易にできるようになる。
小規模システムであれば、MySQLなどのソケットも利用できると思われます。

8
12
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
8
12