# 環境:Ruby 2.2.0, Rails 4.1.1
rvm use 2.2.0
rails new docker-test && cd docker-test
# 基礎控制器
rails g controller welcome index
# config/routes.rb
root 'welcome#index'
# 驗證運行
rails s # 訪問 https://localhost:3000
gem 'unicorn' # 高性能 Rack 服務器
gem 'foreman' # Procfile 進程管理
bundle install
worker_processes Integer(ENV["WEB_CONCURRENCY"] || 3)
timeout 15
preload_app true
before_fork do |server, worker|
Signal.trap 'TERM' do
puts 'Unicorn master intercepting TERM and sending myself QUIT instead'
Process.kill 'QUIT', Process.pid
end
defined?(ActiveRecord::Base) and ActiveRecord::Base.connection.disconnect!
end
after_fork do |server, worker|
Signal.trap 'TERM' do
puts 'Unicorn worker intercepting TERM and doing nothing. Wait for master to send QUIT'
end
defined?(ActiveRecord::Base) and ActiveRecord::Base.establish_connection
end
web: bundle exec unicorn -p $PORT -c ./config/unicorn.rb
foreman start # 本地驗證 https://localhost:5000
# 基礎鏡像
FROM ruby:2.2.0
# 系統依賴
RUN apt-get update && apt-get install -y \
nodejs postgresql-client sqlite3 \
--no-install-recommends \
&& rm -rf /var/lib/apt/lists/*
# Rails 版本鎖定
ENV RAILS_VERSION 4.1.1
RUN gem install rails --version "$RAILS_VERSION"
# 應用目錄
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
# 端口暴露
EXPOSE 3000
ENV PORT=3000
# 先複製 Gemfile 利用緩存
ADD Gemfile /usr/src/app/
ADD Gemfile.lock /usr/src/app/
RUN bundle install --without development test
# 複製應用代碼
ADD . /usr/src/app
# 數據庫遷移(構建時執行)
RUN RAILS_ENV=production rake db:create db:migrate
# 啟動命令
CMD ["foreman", "start"]
# 構建鏡像
docker build -t localhost:5000/your_username/docker-test .
# 運行容器
docker run -d -p 3000:3000 --name docker-test localhost:5000/your_username/docker-test
# 訪問:https://:3000
boot2docker ip # 查看 VM IP
rake docker:all # 完整流水線
rake docker:build # 僅構建
本文展示了從零構建到自動化部署的完整鏈路,理解底層原理後,建議遷移至現代 CI/CD 體系提升效率與可靠性。