Unicorn is an HTTP server for Ruby. It is designed to be used in production environment unlike Webrick which is designed to be used at the time of development on local machine. Because it is very fast, efficient and offers lots of good features like load balancing. At the starting of unicorn server, its master process forks a specific number of processes that is known as workers. The workers will then handle the incoming requests to your application and only accept a request when theyre ready.
The operating system is responsible for handling the forking, and also the circulation of requests between processes that are ready to accept, not the Unicorn. What Unicorn does is the actual checking of workers themselves through the master process. If a worker is taking too much time to complete a task, the master process will kill it and fork a new one.
Configuring Unicorn:
1) First of all we need to add the gem to the Gemfile
gem 'unicorn', '~> 4.8.0
Make sure you change the version number to the most recent one at that particular time of your installation of unicorn. The notation ~> means that any future minor updates will be installed but not the major ones.
than do bundle install, after that we can start configuring it. We will start by creating a file known as unicorn.rb on the local machine in the /config directory of your rails application. The sample file look like as follows:
root = "/var/www/firstApp"
working_directory root
pid "#{root}/tmp/pids/unicorn.pid"
stderr_path "#{root}/log/unicorn.log"
stdout_path "#{root}/log/unicorn.log"
listen "/tmp/unicorn.firstApp.sock"
worker_processes 2
timeout 30
where root is the root directory of your rails project
working_directory The app's working directory and it is set to the variable root we defined above.
pid is the .pid file that will store the process ID of unicorn master process
stderr_path and stdout_path specify the path to stderr and stdout
listen specifies the path to a socket that will listen for a client wanting to make a connection request
worker_processes specifies the number of workers that the master process will fork for client request handling. The more workers you set, the more memory youll need
timeout it indicates the max number of seconds a worker can take to respond for a request before the master process kills it and splits a new one
start Unicorn:
$ unicorn_rails -c /var/www/unicorn/config/unicorn.rb -D
-D is for deamonizes it.
-c specifies the configuration file.
In production you will probably want to pass -E production as well, to run the app in the production environment.
0 Comment(s)