Using UUID as Primary Key in Ruby on Rails With MySQL Guide

Ruby on Rails MySQL UUID Primary Key Guide

A UUID (universally unique identifier) is an identifier standard used in software construction. A UUID is simply a 128-bit value. The meaning of each bit is defined by any of several variants.

For human-readable display, many systems use a canonical format using hexadecimal text with inserted hyphen characters. For example: de305d54-75b4-431b-adb2-eb6b9e546013.

The intent of UUIDs is to enable distributed systems to uniquely identify information without significant central coordination.

Installation
To use UUID as Primary Key you need to add uuidtools gem to your app’s Gemfile:

Gemfile
1
gem 'uuidtools'

Setting up UUID as Primary Key
To set UUID as Primary Key, you need to set id to false and the new UUID column as Primary Key in migration file:

*_create_products.rb
1
2
3
4
5
6
7
8
9
10
class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products, id: false do |t|
      t.string :uuid, limit: 36, primary: true, null: false
      t.string :name, limit: 50, null: false

      t.timestamps
    end
  end
end

Inserting UUID Value into UUID Column
Create UUID helper library in app/lib directory:

uuid_helper.rb
1
2
3
4
5
6
7
8
9
10
11
module UuidHelper
  def self.included(base)
    base.primary_key = 'uuid'
    base.before_create :assign_uuid
  end

  private
  def assign_uuid
    self.uuid = UUIDTools::UUID.timestamp_create().to_s.upcase if uuid.blank?
  end
end

And then include UuidHelper library in Model file:

product.rb
1
2
3
class Product < ActiveRecord::Base
  include UuidHelper
end

Ruby - Check for Nil Without Using an Explicit If

Ruby - Check for nil Without Using an Explicit if

All checks for nil are a condition, but Ruby provides many ways to check for nil without using an explicit if. Watch out for nil conditional checks behind other syntax:

Explicit if with nil?

1
2
3
4
5
if listing.nil?
  nil
else
  listing.name
end

Using other syntax:

Implicit nil check through truthy conditional

1
2
3
if listing
  listing.name
end

Relies on nil being falsey

1
listing && listing.name

Call to try

1
listing.try(:name)

Tips to Improve the Performance of Ruby on Rails Application

Tips to Improve the Performance of Ruby on Rails Application

In this article, I will show you tips to improve performance of Ruby on Rails application. let’s dive into those.

1. Limit Amount of Data in a Controller Method
Thin controllers are easy to test and has a good performance profile because there’s some overhead involved in passing the controller instance variable around. In short, you need to follow “Thin controller and fat model”.

2. Split View in Separate Partials
n this way, views will be easier to read and easier to cache.

3. Choose Right Session Storage
Based on your level of need, choose your session storage carefully. Here are what rails provide:
- CookieStore – Stores everything on the client.
- DRbStore – Stores the data on a DRb server.
- MemCacheStore – Stores the data in a memcache.
- ActiveRecordStore – Stores the data in a database using Active Record.

4. DRY (Don’t Repeat Yourself)
This is the most common things programmers tend to listen and don’t follow. Here is very basic example:

1
2
3
4
5
if Listing.find_by_id(1).name == "Bambo"
  return Listing.find_by_id(1)
else
  return nil
end

It should be written by:

1
2
listing = Listing.find_by_id(1)
if listing.name == "Bambp" then listing else nil end

4. Eager Loading
Eager loading is a way to solve the classic N + 1 query performance problem caused by inefficient use of child objects.

Let’s look at the following code. It will fetch zip of 10 users.

1
2
3
4
5
users = User.all(:limit => 10)

users.each do |user|
  puts user.address.zip
end

11 queries will be executed, 1 for the top and 10. The solution is to rewrite it to eager load address:

1
2
3
4
5
users = User.includes(:address).limit(10)

users.each do |user|
  puts user.address.zip
end

5. Indexing
Database indexing is one of the simplest ways to improve database performance. The insert operation will become slower but will boost up fetching data which is more frequently used in web application.

6. Avoid Dynamism
Although find_by and find_all_by dynamic methods are really cool, the are also kind of slow because each one needs to run through method_missing and parse the filename against the list of columns in database table.

7. Caching
This is the purest way to speed up a rails application. Here are a short example of different types of caching:
- Page Caching
- Action Caching
- Fragment Caching
- SQL Caching
- Asset Caching

8. Image Spriting
In websites, a significant times are consumed for loading large number of images. One way of minimizing is to sprite your images. This will reduce number of images to be served significantly.

9. Minify and GZIP Stylesheets and Javascripts
This is the last point, but an important one. You can reduce size of the stylesheets and javascripts significantly by Minifying it and serve as GZip format. It will improve the performance significantly by reducing request/response time.

So far so good, these are pretty basic guidelines but surely help you to improve your application. Now, the bounce rate of your site should be less and you are expected to be a happier product owner. :)

Tools for Monitoring Performance in Ruby on Rails Application

Tools for Monitoring Performance in Ruby on Rails Application

Here are some tips for you to monitor performance in a Ruby on Rails application. Some tools and tips are equally applicable for other web applications:

1. Rails Logger
The simplest way to get information about performance is to analyze rails log. It will provide you information of the time spent processing each request, broken down into rendering and SQL time. You can also find whether a particular part are cached or the occurrence of cache expiry.

2. Rails Performance Test - Profiling
Profiling helps you to see the details of a performance test and provide an in-depth picture of the slow and memory hungry parts. Each test case is run 1 time in profiling mode.

3. Rails Performance Test - Benchmarking
Through Rails performance test, source of application’s memory or speed bottleneck and can be found. Benchmarking helps find out how fast each performance test runs. Each test case is run 4 times in benchmarking mode.

4. Rails Analyzer
The Rails Analyzer project contains a collection of tools (The Production Log Analyzer, The Action Profiler, Rails Analyzer Tools, The SQL Dependency Grapher) for Rails that let you discover biggest slow spots in your applications allowing you to best focus optimization efforts.

5. Rails Footnote
It is a rails plugin which displays footnotes in your application for easy debugging, such as sessions, request parameters, cookies, filter chain, routes, queries, etc. Even more, it contains links to open files directly in your editor including your backtrace lines.

6. Query Reviewer
Query Reviewer is an advanced SQL query analyzer. It generates a page with explanation output of all SELECT queries, rate a page’s SQL usage, display interactive summary on page.

7. Slim Scrooge
SlimScrooge is an optimization layer to ensure your application only fetches the database content needed to minimize wire traffic, excessive SQL queries and reduce conversion overheads to native Ruby types.
SlimScrooge implements inline query optimization, automatically restricting the columns fetched based on what was used during previous passes through the same part of your code.

8. New Relic
New Relic is the all-in-one web application performance tool that lets you see performance from the end user experience down to the line of application code. It will also list the errors if such occurrence occur.

9. Rack-Bug
It is a debugging toolbar for Rack applications implemented as middleware.

10. Sidekiq
Sidekiq uses threads to handle many jobs at the same time in the same process. It does not require Rails but will integrate tightly with Rails 3/4 to make background processing dead simple.

11. Firebug
Firebug is a firefox plugin and a very powerful tool. Apart from many outstanding features, it helps to monitor network performance. You can see the load time of each files (when they started to load and when they are completed), filter it by type (e.g. javascript or CSS) and examining http headers.

So far so good, you can suggest more. These are a mere introduction. You can try those out and examine the health of your application. I have a plan to write another one with tips regarding enhancing performance based on the generated health report of a web application. Stay tuned for that!

Ruby on Rails Company

This article is about what makes a Ruby on Rails company stand out in the market. I am going to talk about what clients look for when they hire a Ruby on Rails company.

Experience and Expertise
When hiring a Ruby on Rails company, clients generally look for expert engineers. In most job circulars you will see that they are asking for 2 to 5 or more years of expertise. There is a reason why clients prefer expertise. The biggest market for Ruby on Rails lies in startups. Startups need to do more with less. Ruby on Rails help them to quickly build software with limited budget. However, the nature of this framework is such that it takes time to master.

Communication
Communication is extremely important for a Ruby on Rails company. It applies to both onsite and offsite developers. As a developer, if you cannot convey your message properly, no matter how expert you are, you will not impress the client. Communication is vital from the very first meeting to post delivery service.

Development Method and Project Management Style
This is mostly applicable for remote developers. Clients want to know if the Ruby on Rails company follow any specific development method. They are also interested in the team’s project management style. You will often find clients asking about Agile, TDD etc.

Let me share the diagram that shows how we develop software.

Ruby on Rails Company

So far so good, If you are setting up a Ruby on Rails development company, these are the areas you should be concerned about. If you excel in these areas, you will definitely get more clients. Ruby on Rails clients, despite their vastly different projects, have similar technical requirements.

Add Progress Bar in Ruby on Rails Application

Add Progress Bar in Ruby on Rails Application

Okay, today I would like to show how to add progress bar in Ruby on Rails application. For add progress bar in Ruby on Rails application I use nprogress-rails ruby gem.

Installation
Add nprogress-rails ruby gem to Gemfile:

Gemfile
1
gem 'nprogress-rails'

And then open terminal type:

1
$ bundle

Usage
Add the requires to the application.js:

application.js
1
2
//= require nprogress
//= require nprogress-turbolinks

Also, into the application.css.scss:

application.css.scss
1
2
*= require nprogress
*= require nprogress-bootstrap

And then, add NProgress.start(); to application.js for loading progress bar whenever you load each pages:

application.js
1
2
3
$(document).ready(function() {
  NProgress.start();
});

So far so good, let enjoy the progress bar in your application. Thank for reading :)

The Most Gem That I Use for Developing Ruby on Rails Project

The most gem that I use for developing ruby on rails project

activerecord

1. kaminari
Description: A Scope & Engine based, clean, powerful, customizable and sophisticated paginator for modern web app frameworks and ORMs.
Source: https://github.com/amatsuda/kaminari

2. i18n-active_record
Description: Use to lookup translations in the database.
Source: https://github.com/svenfuchs/i18n-active_record

3. paperclip
Description: Paperclip is intended as an easy file attachment library for Active Record.
Source: https://github.com/thoughtbot/paperclip

4. paperclip-meta
Description: Use for adding width, height, and size to paperclip images.
Source: https://github.com/teeparham/paperclip-meta

5. swf_file
Description: SWF File is lightweight gem to read swf file headers from within a Ruby application.
Source: https://github.com/DBA/swf_file

delayed_job

1. delayed_job_active_record
Description: delayed_job_active_record encapsulates the common pattern of asynchronously executing longer tasks in the background.
Source: https://github.com/collectiveidea/delayed_job

2. delayed_job_web
Description: Resque like web interface for delayed job.
Source: https://github.com/ejschmitt/delayed_job_web

mongoid

1. mongoid
Description: Mongoid is an ODM (Object-Document-Mapper) framework for MongoDB in Ruby.
Source: https://github.com/mongoid/mongoid

2. mongoid-rails-instrumentation
Description: Add additional information to rails logs about total time for MongoDB queries in action processing.
Source: https://github.com/fredjean/mongoid-rails-instrumentation

solr

1. rsolr
Description: A simple, extensible Ruby client for Apache Solr.
Source: https://github.com/rsolr/rsolr

views

1. haml-rails
Description: Haml-rails provides Haml generators for rails 3.
Source: https://github.com/indirect/haml-rails

2. simple_form
Description: simple_form aims to be as flexible as possible while helping you with powerful components to create your form.
Source: https://github.com/plataformatec/simple_form

3. unicode
Description: Unicode string manipulation library for Ruby.
Source: https://github.com/blackwinter/unicode

4. wicked_pdf
Description: Wicked PDF uses the shell utility wkhtmltopdf to serve a PDF file to a user from HTML.
Source: https://github.com/mileszs/wicked_pdf

5. wkhtmltopdf-binary
Description: Provides binaries for WKHTMLTOPDF project in an easily accessible package.
Source: https://rubygems.org/gems/wkhtmltopdf-binary

6. best_in_place
Description: Best in Place is a jQuery based AJAX Inplace-Editor that takes profit of RESTful server-side controllers to allow users to edit stuff with no need of forms.
Source: https://github.com/bernat/best_in_place

7. mustache
Description: Mustache is a framework-agnostic way to render logic-free views.
Source: https://github.com/mustache/mustache

8. olive
Description: is the rails helper​ gem that enables to use content_for in controllers.
Source: https://github.com/Bunlong/olive

9. activenavbar
Description: is the gem that use to set the active navbar link, a link becomes active when you click on it.
Source: https://github.com/Bunlong/activenavbar

utils

1. uuidtools
Description: uuidtools was designed to be a simple library for generating any of the various types of uuids.
Source: https://github.com/sporkmonger/uuidtools/tree

2. geoip
Description: The Ruby gem for querying Maxmind.com’s GeoIP database, which returns the geographic location of a server given its IP address.
Source: https://github.com/cjheath/geoip

3. fakie
Description: Libphonenumber Ruby wrapper.
Source: https://github.com/seesawco/fakie

auth

1. devise
Description: devise is a flexible authentication solution for Rails.
Source: https://github.com/plataformatec/devise

2. devise-encryptable
Description: Devise encryptable behavior.
Source: https://github.com/plataformatec/devise-encryptable

3. CanCan
Description: CanCan is an authorization library for Ruby on Rails.
Source: https://github.com/ryanb/cancan

4. rolify
Description: Role management library with resource scoping.
Source: https://github.com/RolifyCommunity/rolify

aws

1. aws-sdk
Description: The official AWS SDK for Ruby.
Source: https://github.com/aws/aws-sdk-ruby

misc

1. passenger
Description: Phusion Passenger™ is a web server and application server, designed to be fast, robust and lightweight.
Source: https://github.com/phusion/passenger

2. whenever
Description: Whenever is a Ruby gem that provides a clear syntax for writing and deploying cron jobs.
Source: https://github.com/javan/whenever

3. ruby-graphviz
Description: Ruby interface to the GraphViz graphing tool.
Source: https://github.com/glejeune/Ruby-Graphviz/

rake

1. sitemap_generator
Description: SitemapGenerator is the easiest way to generate Sitemaps in Ruby.
Source: https://github.com/kjvarga/sitemap_generator

2. fog
Description: fog is the Ruby cloud services library.
Source: https://github.com/fog/fog

3. progressbar
Description: Ruby/ProgressBar is a text progress bar library for Ruby.
Source: https://github.com/peleteiro/progressbar

4. parallel
Description: Ruby parallel processing made simple and fast.
Source: https://github.com/grosser/parallel

5. terminal-table
Description: Ruby ASCII Table Generator, simple and feature rich.
Source: https://github.com/tj/terminal-table

production

1. dalli
Description: Dalli is a high performance pure Ruby client for accessing memcached servers.
Source: https://github.com/mperham/dalli

2. exception_notification
Description: The Exception Notification gem provides a set of notifiers for sending notifications when errors occur in a Rack/Rails application. The built-in notifiers can deliver notifications by email, campfire rooms or via webhooks.
Source: https://github.com/smartinez87/exception_notification

3. newrelic_rpm
Description: New Relic is a performance management system, developed by New Relic, Inc. It provides you with deep information about the performance of your Rails or Ruby application as it runs in production.
Source: https://github.com/newrelic/rpm

development & test

1. brakeman
Description: Brakeman is a static analysis tool which checks Ruby on Rails applications for security vulnerabilities.
Source: https://github.com/presidentbeef/brakeman

2. ffaker
Description: A library for generating fake data such as names, addresses, and phone numbers.
Source: https://github.com/EmmanuelOga/ffaker

3. binding_of_caller
Description: Retrieve the binding of a method’s caller.
Source: https://github.com/banister/binding_of_caller

guard

4. rb-inotify
Description: This is a simple wrapper over the inotify Linux kernel subsystem for monitoring changes to files and directories.
Source: https://github.com/nex3/rb-inotify

5. guard-rspec
Description: Guard::RSpec allows to automatically & intelligently launch specs when files are modified.
Source: https://github.com/guard/guard-rspec

6. guard-jasmine
Description: Guard::Jasmine automatically tests your Jasmine specs when files are modified.
Source: https://github.com/guard/guard-jasmine

7. guard-jasmine
Description: Zeus preloads your Rails app so that your normal development tasks such as console, server, generate, and specs/tests take less than one second.
Source: https://github.com/burke/zeus

javascript

8. jasminerice
Description: Pain free coffeescript testing.
Source: https://github.com/bradphelan/jasminerice

console

9. pry
Description: An IRB alternative and runtime developer console.
Source: https://github.com/pry/pry

10. pry-debugger
Description: Fast execution control in Pry.
Source: https://github.com/nixme/pry-debugger

11 pry-rails
Description: Avoid repeating yourself, use pry-rails instead of copying the initializer to every rails project. This is a small gem which causes rails console to open pry.
Source: https://github.com/rweng/pry-rails

web server

12. thin
Description: A very fast & simple Ruby web server.
Source: https://github.com/macournoyer/thin/

rspec, capybara and shoulda

13. rspec-rails
Description: rspec-rails is a testing framework for Rails.
Source: https://github.com/rspec/rspec-rails

14. headless
Description: Ruby wrapper for Xvfb, the virtual framebuffer.
Source: https://github.com/leonid-shevtsov/headless

15. factory_girl_rails
Description: factory_girl_rails provides Rails integration for factory_girl.
Source: https://github.com/thoughtbot/factory_girl_rails

16. capybara
Description: Capybara helps you test web applications by simulating how a real user would interact with your app.
Source: https://github.com/jnicklas/capybara

17. shoulda-matchers
Description: shoulda-matchers provides Test::Unit- and RSpec-compatible one-liners that test common Rails functionality.
Source: https://github.com/thoughtbot/shoulda-matchers

development

1. rails-erd
Description: Generate Entity-Relationship Diagrams for Rails applications.
Source: https://github.com/voormedia/rails-erd

2. better_errors
Description: Better Errors replaces the standard Rails error page with a much better and more useful error page.
Source: https://github.com/charliesome/better_errors

3. foreman
Description: Manage Procfile-based applications.
Source: https://github.com/ddollar/foreman

test

1. simplecov
Description: SimpleCov is a code coverage analysis tool for Ruby.
Source: https://github.com/colszowka/simplecov

2. json_spec
Description: Easily handle JSON in RSpec and Cucumber.
Source: https://github.com/collectiveidea/json_spec

3. database_cleaner
Description: Strategies for cleaning databases in Ruby. Can be used to ensure a clean state for testing.
Source: https://github.com/DatabaseCleaner/database_cleaner

assets

1. asset_sync
Description: Asset Sync is built to run with the new Rails Asset Pipeline feature introduced in Rails 3.1. After you run bundle exec rake assets:precompile your assets will be synchronised to your S3 bucket, optionally deleting unused files and only uploading the files it needs to.
Source: https://github.com/rumblelabs/asset_sync

2. sass-rails
Description: This gem provides official integration for Ruby on Rails projects with the Sass stylesheet language.
Source: https://github.com/rails/sass-rails

3. bootstrap-sass
Description: Official Sass port of Bootstrap.
Source: https://github.com/twbs/bootstrap-sass

4. jquery-fileupload-rails
Description: jQuery File Upload integrated for Rails Asset Pipeline.
Source: https://github.com/tors/jquery-fileupload-rails

5. bootstrap-wysihtml5-rails
Description: WYSIWYG editor for Bootstrap, integrated in Rails assets pipeline.
Source: https://github.com/Nerian/bootstrap-wysihtml5-rails

9 Things to Be a Professional Programmer

Professional Programmer

I’ve been reading a lot of code, design pattern, leading and project management book for last few years and I’ve noted many good points how to be a Professional Programmer. Let enjoy reading and become “Go-to guy” together.

1. Knows the domain of their project
As a professional programmer, your job is more than just reading requirement specifications and code the software. You should also know where and how the project is being used by the its users in the real world.

This means that if you are working on an accounting software, you should at least have some basic knowledge about accounting. It is not necessary to become an expert in the subject, but a little knowledge helps a big way when solving problems and coming up with solutions.

2. Is a team player
As a professional programmer, you should of course be polite and helpful towards other people. When other people ask for help, you should treat them in the same manner as you wish someone would treat you, if you were stuck. You should always offer help and welcome help from others.

Also, you should not build a wall around yourself or your code. It is important to remember that you don’t own the code, but rather the team does. So instead of dismissing anyone from working in, or even seeing, the code, it should be encouraged. This will help you grow as a programmer, since it opens up for feedback, but it also greatly benefits the group and the project itself.

Over time, teams slowly grows better and better as well, resulting in team members will eventually know each others strengths and weaknesses. When this happens the team becomes very efficient on solving issues as a group. Since it takes time to build up a solid team, when a project ends, it is smarter to give the team a new project, rather than disbanding the whole group.

3. Takes responsibility
As a professional programmer, you take responsibility for your code. It is your job to know what your code does and know that all of the code works. When coding you should always aim to cause no harm in your project, by always aiming to get the error rate as close to zero as possible.

This is done by simple writing tests. Tested code gives you more confident about your work, knowing the fact that what deliver is at top class and checked against errors. The QA department should never find bugs. An entire project with tested code also gives the programmer more confident to actually do something about smelly code.

Unit and acceptance tests should be done automatically (due to it is significantly cheaper than manually testing) by using a continuous integration system. These tests should be running all the time, every time a programmer commits code to the project. If a test breaks, it should be fixed as soon as possible.

As a professional programmer is also strongly for Test Driven Development. The TDD discipline forces the programmer to think about good design and structuring up their code to make it test-friendly, it is actually unprofessional not to use TDD.

4. Knows patterns and disciplines
As a professional programmer, it is your responsibility to write high-quality, tested, clean code. This includes knowing design patterns, principles, methods, disciplines and artifacts.

Since the software development industry is changing constantly with new ideas and tools around the next corner, it is also equally important that you keep yourself up to date on new disciples and techniques.

5. Remains calm during hectic situations
As a professional developer, you should always remain calm during hectic and stressful situations. Instead, try and think out the best solution to resolve your situation and the inform your superiors about the situation and ask for their feedback and suggestions.

Acting on panic will most likely just result in making more errors. In emergencies, you could try and pair program with a colleague. Not only will this probably decrease the number of new errors, but pair programming is also a great source of sharing knowledge between team members.

6. Keeps practicing profession
As a professional programmer, you should spend time caring for your profession. Just like in any other profession, practice gives performance, skill and experience.

It is your own responsibility to keep training yourself by reading, practicing and learning - actually anything that helps you grow as a software developer and helps you get on board with the constant industry changes.

An important note is this should be done on your own time, not on your employer’s. It is not their responsibility to train you, but your own. However, do not mistake this with you should be doing your job during this time. This time should be dedicated for you and your own enjoyment only. You should do anything that interests you. If you work 40 hours a week ,you should spend around 20 additional hours enhancing your own profession.

7. Rests
As a professional programmer, you should know that being a software developer is a very intellectual and exhausting job. It is important that you don’t overwork yourself, but rather find a balance in life with your job. Being a well rested developer makes you more focused and makes you perform better.

8. Knows the value of time
As a professional programmer, you should know the value of time. Your time is expensive and should not be wasted, meaning you should use your time wisely and know things like the the high cost of meetings. Politely decline meetings that do not benefit you, or if your present doesn’t benefit anyone.

Meetings should also have a clear agenda and a goal. If you notice that a meeting is getting boring and does not benefit you anymore, or if the agenda gets abandoned or if the meeting simple gets high-jacked, either request a new topic or politely leave the meeting. You probably have better things to do then remain seated.

9. Is never afraid to say no
As a professional programmer should not be afraid to say no. If you know something is unrealistic (such as an estimation, a deadline, a requirement, etc) it is expected from you to speak up. Not most of the time - but all the time.

You shouldn’t even say you can try, as that will give a false impression to everyone that the task is doable, and maybe even worse, it turns you into a liar which can hurt your reputation among your superiors and colleagues. Instead, try and rephrase yourself and explain your concerns. Be clear and specific about the problems and dates and times.

The definition of an estimate is interpreted by different people. For business people, estimations are commitments. For software developers, estimations are guesses, measured in probability.

You should only do commitments, when you are certain it can be done. When professional commits to something, the provide with a hard number and makes certain the job before the deadline.

So far so good, the more you read the more you know the more you know the more places you’ll go. See you!!! :)

EngineX/Nginx Installation and Basic Usage

Nginx plus

Nginx is available in most Linux distributions. In this article, I use Ubuntu 14.10.

Installation
Open your terminal and run the following command as root user:

1
apt-get install nginx

Now Nginx is installed, you can use the startup script to start, stop or restart the Web server:

1
2
3
/etc/init.d/nginx start
/etc/init.d/nginx stop
/etc/init.d/nginx restart

Most configuration changes do not require to restart, in which case you can use the reload command. It is generally a good idea to test the Nginx configuration file for errors before reloading:

1
2
nginx -t
/etc/init.d/nginx reload

Let’s go ahead and start the server:

1
/etc/init.d/nginx start

Nginx now should be running on your machine. If you open http://127.0.0.1/ or http://localhost in your browser, you should see a page with “Welcome to nginx!”.

Main Configuration File (/etc/nginx/nginx.conf)
Now Nginx is installed, let’s take a look at its config file that located at /etc/nginx/nginx.conf. This file contains the server-wide settings for Nginx, and it should look similar to this:

/etc/nginx/nginx.conf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
user www-data;
worker_processes  1;
error_log  /var/log/nginx/error.log;
pid  /var/run/nginx.pid;

events {
  worker_connections  1024;
}

http {
  include /etc/nginx/mime.types;
  default_type application/octet-stream;
  access_log /var/log/nginx/access.log;
  sendfile on;
  keepalive_timeout 65;
  tcp_nodelay on;
  gzip on;
  include /etc/nginx/sites-enabled/*;
}

We are not going to change any of these settings, but let’s talk about some of them to help us understand how Nginx works:

worker_processes setting tells Nginx how many child processes to start. If your server has more than one processor or is performing large amounts of disk IO, you might want to try increasing this number to see if you get better performance.

worker_connections setting limits the number of concurrent connections per worker process. To determine the maximum number of concurrent requests, you simply multiply worker_processes by worker_connections.

error_log and access_log settings indicate the default logging locations. You also can configure these settings on a per-site basis, as you will see later in the next article. Like Apache, Nginx is configured to run as the www-data user, but you easily can change this with the user setting. The startup script for Nginx needs to know the process ID for the master process, which is stored in /var/run/nginx.pid, as indicated by the pid setting.

sendfile setting allows Nginx to use a special Linux system call to send a file over the network in a very efficient manner. The gzip option instructs Nginx to compress each response, which uses more CPU but saves bandwidth and decreases response time. Additionally, Nginx provides another compression module called gzip precompression (available as of version 0.6.24). This module looks for a compressed copy of the file with a .gz extension in the same location and serves it to gzip-enabled clients. This prevents having to compress the file each time it’s requested.

The last setting we are concerned with is the include directive for the sites-enabled directory. Inside /etc/nginx, you’ll see two other directories, /etc/nginx/sites-available and /etc/nginx/sites-enabled. For each Web site you want to host with Nginx, you should create a config file in /etc/nginx/sites-available, then create a symlink in /etc/nginx/sites-enabled that points to the config file you created. The main Nginx config file includes all the files in /etc/nginx/sites-enabled. This helps organize your configuration files and makes it very easy to enable and disable specific Web sites.

So far so good, next article I will show you how to work with Nginx. :)

EngineX/Nginx the High-Performance Web Server and Reverse Proxy

Nginx plus

Apache is the most popular Web server and one of the most successful open-source projects of all time. Apache has served more Web sites than any other Web server. Many of the world’s largest Web sites, including YouTube, Facebook, Wikipedia , use Apache to serve billions of page views per month. Over the years, Apache has proven itself to be a very stable, secure and configurable Web server.

Although Apache is an excellent Web server, what if there were an alternative with the same functionality, a simpler configuration and better performance?
A Web server exists with better performance, and it’s called Engine X or Nginx.

Nginx is a high-performance Web server and reverse proxy. Nginx is used by some of the largest Web sites in the US, including WordPress etc, and it’s currently serving about 500 million requests per day. Nginx is the fourth-most-popular Web server, and it is currently serving more than two million Web sites.

Why Nginx?
Like Apache, Nginx has all the features you would expect from a leading Web server:
1. Static file serving
2. SSL/TLS support
3. Virtual hosts
4. Reverse proxying
5. Load balancing
6. Compression
7. Access controls
8. URL rewriting
9. Custom logging
10. Server-side includes
11. Caching

The main advantages of Nginx over Apache are performance and efficiency. Nginx is able to serve more requests per second with less resources because of its architecture. It consists of a master process, which delegates work to one or more worker processes. Each worker handles multiple requests in an event-driven or asynchronous manner using special functionality from the Linux kernel. This allows Nginx to handle a large number of concurrent requests quickly with very little overhead. Apache can be configured to use either a process per request (pre-fork) or a thread for each request (worker). Although Apache’s threaded mode performs much better than its pre-fork mode, it still uses more memory and CPU than Nginx’s event-driven architecture.

So far so good, next article I will show you how to install & use it. See you!