用nginx和rails配置负载均衡
Source code: https://github.com/zhulinpinyu/lbnr
Requirement
- docker
- docker-compose
I. Build rails app image
HomeHelper
require 'socket'
module HomeHelper
def local_ip
orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily
UDPSocket.open do |s|
s.connect '192.168.99.100', 1
s.addr.last
end
ensure
Socket.do_not_reverse_lookup = orig
end
end
Home#index
<h1>Home#index</h1>
<p>Hostname: <%= Socket.gethostname %></p>
<p>IP: <%= local_ip %></p>
Dockerfile
FROM rails:4.2.3
RUN bundle config 'mirror.https://rubygems.org' 'https://ruby.taobao.org'
ADD Gemfile /lbnr/Gemfile
ADD Gemfile.lock /lbnr/Gemfile.lock
RUN cd /lbnr && bundle install
ADD . /lbnr
WORKDIR /lbnr
ENTRYPOINT ["rails","s","-e","production","-b","0.0.0.0"]
CMD ["-p","3000"]
Build lbnr_app image
docker build -t lbnr_app .
II. Build nginx image
Dockerfile
FROM nginx:latest
RUN rm -fr /usr/share/nginx/html
ADD nginx.conf /etc/nginx/conf.d/default.conf
docker-compose.yml
web:
build: .
ports:
- 80:80
container_name: "web"
Build nginx_web image
docker-compose build
III. Start 3 App Server
docker-compose.yml
app1:
image: lbnr_app
command: -p 3001
ports:
- "3001:3001"
container_name: "app1"
app2:
image: lbnr_app
command: -p 3002
ports:
- "3002:3002"
container_name: "app2"
app3:
image: lbnr_app
command: -p 3003
ports:
- "3003:3003"
container_name: "app3"
docker-compose up
IV. Start Nginx Web Server
docker-compose.yml
web:
build: .
ports:
- 80:80
container_name: "web"
start web
docker-compose up
V. Result
1st access
2nd access
3rd access
4th access
5th access (start next repeat)
参考: http://liubin.org/2014/02/18/rails-cluster-with-ruby-load-balancer-using-docker/
https://github.com/Muriel-Salvan/rails-cluster-docker/tree/master/server