Skip to content

Instantly share code, notes, and snippets.

@qpowell
Last active October 17, 2017 11:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qpowell/6c582fe84c728d940f83 to your computer and use it in GitHub Desktop.
Save qpowell/6c582fe84c728d940f83 to your computer and use it in GitHub Desktop.
Unicorn setup for local development environment and Heroku

Unicorn setup for local development environment and Heroku

More info can be found on Heroku: Deploying Rails Applications with Unicorn

  1. Add unicorn, rack-timeout, and foreman to your 'Gemfile'.

     gem 'unicorn'
     gem 'rack-timeout'
     
     group :development do
       gem 'foreman'
     end
    
  2. Run bundle install

  3. Create Procfile at the root of the project and add the following line: web: bundle exec unicorn -p $PORT -c ./config/unicorn.rb

  4. Create unicorn config at 'config/unicorn.rb'

       # Example - https://devcenter.heroku.com/articles/rails-unicorn#config
       
       worker_processes ENV["RAILS_ENV"] == "development" ? 1 : Integer(ENV["WEB_CONCURRENCY"] || 2)
       timeout 60
       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
    
  5. Set Rack::Timeout in 'config/initializers/timeout.rb'

     # Heroku recommends setting this value to a lower value than the 'timeout' in your unicorn config
     Rack::Timeout.timeout = 55 # in seconds
    
  6. Create 'script/server' to start unicorn locally:

     #!/usr/bin/env ruby -w
     puts "Starting server..."
     exec "bundle exec foreman start"
    

    Note: to make script/server executable, type this in the terminal: chmod +x script/server

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment