Tutorials \ Linux \ Web Servers

Deploy Nginx on CentOS 6

Overview

Nginx is designed for high performance and efficient system resource usage. These may not seem important when you first start out, but as your application scales to thousands of concurrent users, every millisecond of response time and every megabyte of memory starts to count. If your server software isn’t using resources efficiently, you may severely limit the amount of users your server can handle before your app starts feeling slugish.

Another benefit of Nginx is its ease of configuration and use. The configuration files are easy to understand and use plain english. This means less time is used up refining and optimizing the configuration, and more time deploying applications.

Most sites use Nginx as a proxy, serving up static content and then forwarding requests to dynamic content hosted Apache servers. However, recent versions of Nginx are now capable of FastCGI processing, allowing it to host dynamic content powered by PHP, Python, and many others.

Install Nginx

As of the date of this articile, Nginx is not in CentOS’s default repositories. This leaves us with two choices: build it from source or add the Nginx repository to install it using YUM.

Install From Repository

  1. Navigate to /etc/yum.repos.d
  2. Create a repo configuration file for Nginx
    vi nginx.repo
  3. Add the following lines to nginx.conf
    [nginx]
       name=nginx repo
       baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
       gpgcheck=0
       enabled=1
  4. Save changes and exit the text editor.
  5. Install Nginx
    yum install nginx

Install Nginx From Source

  1. Ensure you have the required development packages installed on your system. They will be need to compile the source files.
    yum groupinstall "development tools"
  2. Download the latest version from Nginx’s website uring wget. The latest version at the time of this tutorial is 1.5.8.
    wget http://nginx.org/download/nginx-1.5.8.tar.gz
  3. Untar the downloaded file.
    tar -xvf nginx-1.5.8.tar.gz
  4. Navigate into the new nginx directory
    cd nginx-1.5.8
  5. To enable the rewrite module, install the PCRE development package.
    yum install pcre-devel
  6. To enabled GZip capabilities, install the zlib developement package.
    yum install zlib-devel
  7. Prepare the source files to be compiled on your server.
    ./configure
  8. Compile Nginx from the source files
    make install
  9. Copy the new Nginx binary to /usr/sbin
    cp /usr/local/nginx/sbin/nginx /usr/sbin/nginx
  10. Make the Nginx directory in /etc
    mkdir -p /etc/nginx
  11. Copy the nginx.conf template into /etc/nginx
    cp /usr/local/nginx/conf/nginx.conf /etc/nginx/nginx.conf
  12. Copy the mime.types template into /etc/nginx
    cp /usr/local/gninx/conf/mime.types /etc/nginx
  13. Create the Nginx service account
    useradd --shell /sbin/nologin nginx
  14. Create the Nginx log directory
    mkdir -p /var/log/nginx
  15. Create an Nginx startup script file.
    touch /etc/init.d/nginx
  16. Open the startup script into a text editor and add the following lines
    #!/bin/sh
    #
    # nginx        Startup script for nginx
    #
    # chkconfig: - 85 15
    # processname: nginx
    # config: /etc/nginx/nginx.conf
    # config: /etc/sysconfig/nginx
    # pidfile: /var/run/nginx.pid
    # description: nginx is an HTTP and reverse proxy server
    #
    ### BEGIN INIT INFO
    # Provides: nginx
    # Required-Start: $local_fs $remote_fs $network
    # Required-Stop: $local_fs $remote_fs $network
    # Default-Start: 2 3 4 5
    # Default-Stop: 0 1 6
    # Short-Description: start and stop nginx
    ### END INIT INFO
    
    # Source function library.
    . /etc/rc.d/init.d/functions
    
    if [ -f /etc/sysconfig/nginx ]; then
        . /etc/sysconfig/nginx
    fi
    
    prog=nginx
    nginx=${NGINX-/usr/sbin/nginx}
    conffile=${CONFFILE-/etc/nginx/nginx.conf}
    lockfile=${LOCKFILE-/var/lock/subsys/nginx}
    pidfile=${PIDFILE-/var/run/nginx.pid}
    SLEEPMSEC=100000
    RETVAL=0
    
    start() {
        echo -n $"Starting $prog: "
    
        daemon --pidfile=${pidfile} ${nginx} -c ${conffile}
        RETVAL=$?
        echo
        [ $RETVAL = 0 ] && touch ${lockfile}
        return $RETVAL
    }
    
    stop() {
        echo -n $"Stopping $prog: "
        killproc -p ${pidfile} ${prog}
        RETVAL=$?
        echo
        [ $RETVAL = 0 ] && rm -f ${lockfile} ${pidfile}
    }
    
    reload() {
        echo -n $"Reloading $prog: "
        killproc -p ${pidfile} ${prog} -HUP
        RETVAL=$?
        echo
    }
    
    upgrade() {
        oldbinpidfile=${pidfile}.oldbin
    
        configtest -q || return 6
        echo -n $"Staring new master $prog: "
        killproc -p ${pidfile} ${prog} -USR2
        RETVAL=$?
        echo
        /bin/usleep $SLEEPMSEC
        if [ -f ${oldbinpidfile} -a -f ${pidfile} ]; then
            echo -n $"Graceful shutdown of old $prog: "
            killproc -p ${oldbinpidfile} ${prog} -QUIT
            RETVAL=$?
            echo
        else
            echo $"Upgrade failed!"
            return 1
        fi
    }
    
    configtest() {
        if [ "$#" -ne 0 ] ; then
            case "$1" in
                -q)
                    FLAG=$1
                    ;;
                *)
                    ;;
            esac
            shift
        fi
        ${nginx} -t -c ${conffile} $FLAG
        RETVAL=$?
        return $RETVAL
    }
    
    rh_status() {
        status -p ${pidfile} ${nginx}
    }
    
    # See how we were called.
    case "$1" in
        start)
            rh_status >/dev/null 2>&1 && exit 0
            start
            ;;
        stop)
            stop
            ;;
        status)
            rh_status
            RETVAL=$?
            ;;
        restart)
            configtest -q || exit $RETVAL
            stop
            start
            ;;
        upgrade)
            upgrade
            ;;
        condrestart|try-restart)
            if rh_status >/dev/null 2>&1; then
                stop
                start
            fi
            ;;
        force-reload|reload)
            reload
            ;;
        configtest)
            configtest
            ;;
        *)
            echo $"Usage: $prog {start|stop|restart|condrestart|try-restart|force-reload|upgrade|reload|status|help|configtest}"
            RETVAL=2
    esac
    
    exit $RETVAL
  17. Open the Nginx configuration file into a text editor and modify the highlighted areas to match your system..
    user  nginx;
    
    # Set value to number of process cores
    worker_processes  2;
    
    error_log  /var/log/nginx/error.log warn;
    pid        /var/run/nginx.pid;
    
    events {
        worker_connections  1024;
    }
    
    http {
        include       /etc/nginx/mime.types;
        default_type  application/octet-stream;
    
        log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                          '$status $body_bytes_sent "$http_referer" '
                          '"$http_user_agent" "$http_x_forwarded_for"';
    
        access_log  /var/log/nginx/access.log  main;
    
        sendfile        on;
        #tcp_nopush     on;
    
        keepalive_timeout  65;
    
        gzip  on;
    
        include /etc/nginx/conf.d/*.conf;
    }
  18. Test your install by starting the Nginx daemon
    service nginx start

Configure Nginx

  1. Open the Nginx configuration file
    vi /etc/nginx/nginx.conf
  2. Modify the worker_process value to reflect the number of processor cores installed in the server.
    worker_processes 2
  3. To enable gzip compression, find the following line:
    #gzip on
    And uncomment it
    gzip on
  4. Save changes and exit the text editor.
  5. Restart the Nginx daemon to apply your changes.
    service nginx restart
  6. Configure Nginx to automatically start after reboot.
    chkconfig nginx on

Configure The Default Website

  1. Open the default website configuration file.
    vi /etc/nginx/conf.d/default.conf
  2. To set the listening port, find the following line and modify it’s value:
    listen 80;
  3. Set the DNS hostname of your website by finding the following line and replacing localhost with the name of your server.
    server_name localhost;
  4. The default website root directory is /usr/share/nginx/html. To change it, find the following lines and replace the highlighted value with the desired file path.
    location / { 
         root /usr/share/nginx/html; 
         index index.html index.htm; 
    }
  5. To modify the default index file, add to or replace the values listed next to index.
  6. Save changes and exit the text editor.

Configure Firewall To Allow HTTP Access

  1. Run the following command to allow HTTP access through IPTables.
    iptables -A INPUT -m state --state NEW -P tcp --dport 80 -j ACCEPT
  2. To permanently save the firewall rule, run the following command.
    /sbin/service iptables save

Conclusion

You now have a web server capable of server content very quickly. However, this deployment will only be capable of serving static files, like HTML, Javascript, and CSS. In a future tutorial, I will walk you through configuring Nginx for PHP.

About the Author Shane Rainville is an I.T. professional with over a decade of experience, ranging from application development to system & infrastructure administration. He's worked with small startups to large corporate companies, using unique and creative solutions to solve problems.

Leave a Comment

comments powered by Disqus