In this chapter, we will begin with the steps necessary to establish a functional setup of Nginx. This process is crucial for the smooth functioning of your web server. There are some required libraries and tools to install the program, some parameters that you will have to decide upon when compiling the binaries, and there may also be some configuration changes to perform on your system.
This chapter covers the following topics:
Downloading and installing the prerequisites to compile the Nginx binaries
Downloading a suitable version of the Nginx source code
Configuring Nginx compile-time options
Controlling the application with an
Configuring the system to launch Nginx automatically on startup
A quick overview of the possibilities offered by the Nginx Plus platform
We have chosen to download the source code of the application and compile it manually, as opposed to installing it using a package manager, such as
Yast. There are two reasons for this choice. First, the package may not be available in the enabled repositories of your Linux distribution. In addition, the repositories that offer to download and install Nginx automatically often contain outdated versions. More importantly, you need to configure a variety of significant compile-time options. As a result of this choice of manual setup, your system will require some tools and libraries for the compilation process.
Depending on the optional modules that you select at compile time, you will perhaps need different prerequisites. You will be guided through the process of installing the most common ones, such as
If your operating system offers the possibility to install the Nginx package from a repository, and you are confident enough that the available version will suit all of your needs with the modules included by default, you could consider skipping this chapter altogether and simply run one the following commands. We still recommend getting the latest version and building it from source seeing as it contains the latest bug fixes and security patches. For a Debian-based operating system, run the following command:
apt-get install nginx
For Red Hat–based operating systems, use the following command:
yum install nginx
Alternatively, you can download and install prebuilt packages from the official Nginx website at http://www.nginx.org.
Nginx is a program written in C, so you will first need to install a compiler tool, such as the GNU Compiler Collection (GCC), on your system. GCC may already be present on your system, but if that is not the case, you will have to install it before going any further.
GCC is a collection of free open source compilers for various languages: C, C++, Java, Ada, FORTRAN, and so on. It is the most commonly used compiler suite in the Linux world, and Windows versions are also available. It supports a vast number of processors such as x86, AMD64, PowerPC, ARM, MIPS, and more.
First, make sure GCC isn't already installed on your system by running the following command:
[email@example.com ~]$ gcc
If you get the following output, it means that GCC is correctly installed on your system and you can skip to the next section:
gcc: no input files
If you receive the following message, you will have to proceed with the installation of the compiler:
~bash: gcc: command not found
GCC can be installed using the default repositories of your package manager. Depending on your distribution, the package manager will vary—
yum for a Red Hat-based distribution,
apt for Debian and Ubuntu,
yast for SuSE Linux, and so on. Here is the typical way to proceed with the download and installation of the GCC package:
[firstname.lastname@example.org ~]# yum groupinstall "Development Tools"
If you use
apt-get to install software packages, run the following command:
[email@example.com ~]# apt-get install build-essentials
If you use another package manager with a different syntax, you will probably find the documentation with the
man utility. Either way, your package manager should be able to download and install GCC correctly after having solved the dependencies automatically. Note that this command not only installs GCC, it also proceeds with downloading and installing all common requirements to build applications from source, such as code headers and other compilation tools.
The Perl Compatible Regular Expression (PCRE) library is required to compile Nginx. The Rewrite and HTTP core modules of Nginx use PCRE for the syntax of their regular expressions, as you will discover in later chapters. You will need to install two packages:
pcre-devel. The first package provides the compiled version of the library, whereas the second one provides development headers and sources to compile projects, which are required in our case. Here are example commands that you can run in order to install both the packages.
If you are using
yum, run the following command:
[firstname.lastname@example.org ~]# yum install pcre pcre-devel
Or you can install all of the PCRE-related packages by using the following command:
[email@example.com ~]# yum install pcre*
If you use
apt-get, run the following command:
[firstname.lastname@example.org ~]# apt-get install libpcre3 libpcre3-dev
If these packages are already installed on your system, you will receive a message saying something like Nothing to do. In other words, the package manager did not install or update any component, as both components are already present on the system.
zlib library provides developers with compression algorithms. It is required for the use of
gzip compression in various modules of Nginx. Again, you can use your package manager to install this component, as it is part of the default repositories. Similar to PCRE, you will need both the library and its source for installation:
yum, run the following command:
[email@example.com ~]# yum install zlib zlib-devel
apt-get, run the following command:
[firstname.lastname@example.org ~]# apt-get install zlib1g zlib1g-dev
These packages install quickly and have no known dependency issues.
The OpenSSL project is a collaborative effort to develop a robust, commercial-grade, full-featured, and open source toolkit implementing the Secure Sockets Layer (SSL v2/v3) and Transport Layer Security (TLS v1) protocols, as well as a full-strength general purpose cryptography library. The project is managed by a worldwide community of volunteers that use the Internet to communicate, plan, and develop the OpenSSL toolkit and its related documentation. For more information, visit http://www.openssl.org.
The OpenSSL library will be used by Nginx to serve web pages over a secure connection. We thus need to install the library and its development package. The process remains the same here—you install
yum, run the following command:
[email@example.com ~]# yum install openssl openssl-devel
apt-get, run the following command:
[firstname.lastname@example.org ~]# apt-get install openssl openssl-dev
Please be aware of the laws and regulations in your own country. Some countries do not allow usage of a strong cryptography. The author, publisher, and the developers of the OpenSSL and Nginx projects will not be held liable for any violations or law infringements on your part.
Now that you have installed all of the prerequisites, you are ready to download and compile the Nginx source code.
This approach to the download process will lead us to discover the various resources at the disposal of server administrators—websites, communities, and wikis - all relating to Nginx. We will also quickly discuss the different version branches available, and eventually select the most appropriate one for our setup.
Although Nginx is a relatively new and growing project, there are already a good number of resources available on the World Wide Web (WWW) along with an active community of administrators and developers.
The official website, http://nginx.org, currently serves as official documentation reference and provides links to download the latest version of the application source code and binaries. A wiki is also available at http://wiki.nginx.org, which offers a wide selection of additional resources, such as installation guides for various operating systems, tutorials related to the different modules of Nginx, and more.
There are several ways to get help in case you should need it. If you have a specific question, you may want to try posting on the Nginx forum: http://forum.nginx.org. An active community of users will answer your questions in no time. Additionally, the Nginx mailing list, which is relayed on the Nginx forum, will also prove to be an excellent resource for any question you may have. If you need direct assistance, there is always a group of regulars helping each other out on the IRC channel
#Nginx on irc.freenode.net.
Another interesting source of information is the blogosphere. A simple query on your favorite search engine should return a good number of blog articles documenting Nginx, its configuration, and its modules.
It's now time to head over to the official website and get started with downloading the source code to compile and install Nginx. Before you do so, let's take a quick look at a summary of the available versions and features that come with them.
Igor Sysoev, a talented Russian developer and server administrator, initiated the project back in 2002. Between the first release in 2004 and the current version, the market share of Nginx has been growing steadily. It now serves nearly 15 percent of websites on the Internet, according to a October 2015 http://netcraft.com survey. The features are plenty and render the application both powerful and flexible at the same time.
There are currently three version branches of the project:
Stable version: This version is usually recommended, as it is approved by both developers and users, but is usually a little behind the mainline version in terms of bugfixes and features.
Mainline version: This is the latest version available for download and comes with the newest developments and bug fixes. It was formerly known as the development version. Although it is generally solid enough to be installed on production servers, there is a tiny chance that you will run into the occasional bug. Thus, if you favor stability over novelty, going for the stable version is recommended.
Legacy version: If, for some reason, you are interested in looking at the older versions, you will find them in the download area at http://www.nginx.org.
A recurring question regarding mainline versions is, are they stable enough to be used on production servers? Cliff Wells, original founder and maintainer of the http://www.nginx.org wiki, believes so: I generally use and recommend the latest development version. It's only bitten me once! Early adopters rarely report critical problems. It is up to you to select the version you will be using on your server, knowing that the instructions given in this book should be valid regardless of the release, as the Nginx developers have decided to maintain overall backward compatibility in new versions. You can find more information on version changes, new additions, and bug fixes in the dedicated change log page on the official website.
As of the stable version 1.8.0, Nginx offers an impressive variety of features, which, contrary to what the title of this book indicates, are not all related to serving HTTP content. Here is a list of the main features of the web branch, quoted from the official website http://www.nginx.org:
Serving static and index files; autoindexing; open file descriptor cache; accelerated reverse proxying with caching; load balancing and fault tolerance.
Accelerated support with caching of FastCGI, uwsgi, Simple Common Gateway Interface (SCGI), and memcached servers; load balancing and fault tolerance; modular architecture. Filters include gzipping, byte ranges, chunked responses, XSLT, SSI, and image transformation filter. Multiple SSI inclusions within a single page can be processed in parallel if they are handled by proxied or FastCGI/uwsgi/SCGI servers.
SSL and TLS SNI support.
Nginx can also be used as a mail proxy server, although this aspect is not closely documented in the book:
User redirection to IMAP/POP3 backend using an external HTTP authentication server
User authentication using an external HTTP authentication server and connection redirection to an internal SMTP backend
POP3: USER/PASS, APOP, AUTH LOGIN/PLAIN/CRAM-MD5
IMAP: LOGIN, AUTH LOGIN/PLAIN/CRAM-MD5
SMTP: AUTH LOGIN/PLAIN/CRAM-MD5
STARTTLS and STLS support
Nginx is compatible with most computer architectures and operating systems, including Windows, Linux, Mac OS, FreeBSD, and Solaris. The application runs well on 32- and 64-bit architectures.
Once you have made your choice about which version you will be using, head over to http://www.nginx.org and find the URL of the file you wish to download. Position yourself in your home directory, which will contain the source code to be compiled, and download the file using
[email@example.com ~]$ mkdir src && cd src [firstname.lastname@example.org src]$ wget http://nginx.org/download/nginx-1.8.0.tar.gz
We will be using version 1.8.0, the latest stable version as of April, 2015. Once downloaded, extract the archive contents in the current folder:
[email@example.com src]$ tar zxf nginx-1.8.0.tar.gz
You have successfully downloaded and extracted Nginx. Now, the next step will be to configure the compilation process in order to obtain a binary that perfectly fits your operating system.
There are usually three steps when building an application from source: the configuration, the compilation, and the installation. The configuration step allows you to select a number of options that will not be editable after the program is built, as it has a direct impact on the project binaries. Consequently, it is a very important stage that you need to follow carefully if you want to avoid surprises later, such as the lack of a specific module or having configuration files located in a random folder.
The process consists of appending certain switches to the
configure command that comes with the source code. The three types of switches that you can activate will be covered later, but let's first study the easiest way to proceed.
If, for some reason, you do not want to bother with the configuration step, such as for testing purposes or simply because you will be recompiling the application in the future, you may simply use the
configure command with no switches. Execute the following three commands to build and install a working version of Nginx, starting with the
[firstname.lastname@example.org nginx-1.8.0]# ./configure
Running this command should initiate a long procedure of verifications to ensure that your system contains all of the necessary components. If the configuration process fails, check the prerequisites section again, as it is the most common cause of errors. For information about why the command failed, you may also refer to the
objs/autoconf.err file, which provides a more detailed report. The
make command will compile the application. This step should not cause any errors as long as the configuration went fine.
[email@example.com nginx-1.8.0]# make [firstname.lastname@example.org nginx-1.8.0]# make install
This last step will copy the compiled files as well as other resources to the installation directory, by default,
/usr/local/nginx. You may need to be logged in as root to perform this operation, depending on permissions granted to the
Again, if you build the application without configuring it, you take the risk of missing out on a lot of features, such as the optional modules and others that we are about to discover.
When running the
configure command, you are offered the possibility to enable some switches that let you specify the directory or file paths for a variety of elements. Note that the options offered by the configuration switches may change according to the version you downloaded. The options listed below are valid with the stable version, as of release 1.8.0. If you use another version, run the
./configure --help command to list the available switches for your setup.
Using a switch typically consists of appending some text to the command line, for instance, using the
[email@example.com nginx-1.8.0]# ./configure --conf-path=/etc/nginx/nginx.conf
Here is an exhaustive list of the configuration switches for configuring paths:
Prerequisites come in the form of libraries and binaries. You should, by now, have them all installed on your system. However, even though they are present on your system, there may be occasions where the configuration script is unable to locate them. The reasons might be diverse, for example, if they were installed in non-standard directories.
In order to solve such problems, you are given the option to specify the path of prerequisites using the following switches (miscellaneous prerequisite-related options have been grouped together):
Modules, which will be detailed in Chapter 4, Module Configuration, need to be selected before compiling the application. Some are enabled by default and some need to be enabled manually, as you will see in the following table.
The following switches allow you to disable modules that are enabled by default:
The following switches allow you to enable modules that are disabled by default:
Other options are available in the configuration script, for example, regarding the mail server proxy feature or event management. These have been enlisted as follows:
Here are a few examples of configuration commands that may be used for various cases. In these examples, the path switches have been omitted, as they are specific to each system and leaving the default values may simply function correctly.
Be aware that these configurations do not include additional third-party modules. Please refer to Chapter 4, Module Configuration, for more information about installing add-ons.
During the configuration, you should take particular care of the
--prefix switch. Many of the future configuration directives (that will be approached in further chapters) will be based on the path you select at this point. While it is not a definitive problem since absolute paths can still be employed, you should know that the prefix cannot be changed once the binaries have been compiled.
There is also another issue that you may run into if you plan to keep up with the times and update Nginx as new versions are released. The default prefix (if you do not override the setting by using the
--prefix switch) is
/usr/local/nginx. This is a path that does not include the version number. Consequently, when you upgrade Nginx, if you do not specify a different prefix, the new install files will override the previous ones, which among other problems, could potentially erase your currently running binaries.
It is thus recommended to use a different prefix for each version you will be using. Use the following command to specify a prefix that is specific to version 1.8.0:
Additionally, to make future changes simpler, you may create a symbolic link
/usr/local/nginx pointing to
/usr/local/nginx-1.8.0. Once you upgrade, you can update the link to make it point to
/usr/local/nginx-newer.version. This will allow the
init script to always make use of the latest installed version of Nginx.
The first example describes a situation where the most important features and modules to serve HTTP and HTTPS content are enabled, and the mail-related options are disabled:
./configure --user=www-data --group=www-data --with-http_ssl_module --with-http_realip_module
As you can see, the command is rather simple and most switches have been left out. The reason for this is that the default configuration is rather efficient, and most of the important modules are enabled. You will only need to include the
http_ssl module to serve HTTPS content, and optionally, the real IP module to retrieve your visitors' IP addresses in case you are running Nginx as backend server.
The next situation includes all available modules, and it is up to you whether you want to use them or not at runtime:
./configure --user=www-data --group=www-data --with-http_ssl_module --with-http_realip_module --with-http_addition_module --with-http_xslt_module --with-http_image_filter_module --with-http_geoip_module --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_stub_status_module --with-http_perl_module --with-http_degradation_module --with-http_spdy_module --with-http_gunzip_module --with-http_auth_request_module
This configuration opens up a wide range of possible configuration options. Chapter 3, HTTP Configuration, to Chapter 6, Apache and Nginx Together, provide more detailed information on module configuration.
With this setup, all optional modules are enabled, thus requiring additional libraries to be installed—
libgeoip for the Geo IP module,
libgd for the Image Filter module,
libxslt for the XSLT module. You may install those prerequisites using your system package manager, for example, by running
yum install libxml2 or
apt-get install libxml2.
This last build configuration is somewhat special, as it is dedicated to enabling mail server proxy features—a darker and less documented side of Nginx. You can enable all mail related features through the following command:
./configure --user=www-data --group=www-data --with-mail --with-mail_ssl_module
If you wish to completely disable the HTTP serving features and only dedicate Nginx to mail proxying, you may add the
In some cases, the
configure command may fail—after a long list of checks, you may receive a few error messages on your terminal. In most (if not all) cases, these errors are related to missing prerequisites or unspecified paths.
In such cases, proceed with the following verifications carefully to make sure you have all it takes to compile the application, and optionally, consult the
objs/autoconf.err file for more details about the compilation problem. This file is generated during the configure process and will tell you exactly which part of the process failed.
There are basically four main prerequisites: GCC, PCRE, zlib, and OpenSSL. The last three are libraries that must be installed in two packages: the library itself and its development sources. Make sure you have installed both for each of them. Refer to the prerequisites section at the beginning of this chapter for additional information. Note that other prerequisites such as LibXML2 or LibXSLT may be required to enable extra modules (for example, in the case of the HTTP XSLT module).
If you are positive that all of the prerequisites were installed correctly, perhaps the issue comes from the fact that the
configure script is unable to locate the prerequisite files. In that case, make sure that you include the configuration switches related to file paths, as described earlier.
For example, the following switch allows you to specify the location of the OpenSSL library files:
./configure [...] --with-openssl=/usr/lib64
The OpenSSL library file will be looked for in the specified folder.
Always remember to check the obvious; everyone makes even the simplest of mistakes sooner or later. Make sure that the directory you placed the Nginx files in has read and write permissions for the user running the configuration and compilation scripts. Also ensure that all paths specified in the
configure script switches are existing, valid paths.
The configuration process is of utmost importance—it generates a makefile for the application depending on the selected switches and performs a long list of requirement checks on your system. Once the
configure script is successfully executed, you can proceed with compiling Nginx.
Compiling the project equates to executing the
make command in the project source directory:
[firstname.lastname@example.org nginx-1.8.0]$ make
A successful build should result in the appearance of a final message:
make: leaving directory. This should be followed by the project source path.
Again, problems might occur at compile time. Most of these problems can originate in missing prerequisites or the specification of invalid paths. If this occurs, run the
configure command again and triple-check the switches and all of the prerequisite options. It may also so happen that you downloaded an overly recent version of the prerequisites, which may not be backwards compatible. In such cases, the best option is to visit the official website of the missing component and download an older version.
If the compilation process was successful, you are ready for the next step: installing the application. The following command must be executed with root privileges:
[email@example.com nginx-1.8.0]# make install
make install command executes the
install section of the
make file. In other words, it performs a few simple operations, such as copying binaries and configuration files to the specified
install folder. It also creates directories to store log and HTML files if these do not already exist. The
make install step is not generally a source of problems, unless your system encounters an exceptional error, such as a lack of storage space or memory.
At this stage, you should have successfully built and installed Nginx. The default location for the output files is
/usr/local/nginx, so we will be basing future examples on this.
The next step is obviously run Nginx for the first time. However, before doing so, it's important to understand the nature of this application. There are two types of computer applications—those that require immediate user input, thus running in the foreground, and those that do not, thus running in the background. Nginx is of the latter type, often referred to as daemon. Daemon names usually come with a trailing "d" and a couple of examples can be mentioned here—
httpd, the HTTP server daemon, is the name given to Apache under several Linux distributions;
named, the name server daemon; or
crond the task scheduler—although, as you will notice, this is not the case for Nginx. When started from the command line, a daemon immediately returns the prompt, and in most cases, does not even bother outputting data to the terminal.
Consequently, when starting Nginx, you will not see any text appear on the screen, and the prompt will return immediately. While this might seem startling, it is, on the contrary, a good sign. It means the daemon was started correctly and the configuration did not contain any errors.
It is of utmost importance to understand the process architecture of Nginx, and particularly the user and groups under which its various processes run. A very common source of trouble when setting up Nginx is invalid file access permissions—due to a user or group misconfiguration, you often end up getting 403 Forbidden HTTP errors because Nginx cannot access the requested files.
There are two levels of processes with possibly different permission sets:
The Nginx master process: This should be started as root. In most Unix-like systems, processes started with the root account are allowed to open TCP sockets on any port, whereas other users can only open listening sockets on a port above 1024. If you do not start Nginx as root, standard ports such as 80 or 443 will not be accessible. Note that the
userdirective that allows you to specify a different user and group for the worker processes will not be taken into consideration for the master process.
The Nginx worker processes: These are automatically spawned by the master process under the account you specified in the configuration file with the user directive (detailed in Chapter 2, Basic Nginx Configuration). The configuration setting takes precedence over the configuration switch you may have specified at compile time. If you did not specify any of those, the worker processes will be started as user
nogroupdepending on your OS).
The Nginx binary accepts command-line arguments to perform various operations, among which is controlling the background processes. To get the full list of commands, you may invoke the help screen using the following commands:
[firstname.lastname@example.org ~]$ cd /usr/local/nginx/sbin [email@example.com sbin]$ ./nginx -h
The next few sections will describe the purpose of these switches. Some allow you to control the daemon and some let you perform various operations on the application configuration.
You can start Nginx by running the Nginx binary without any switches. If the daemon is already running, a message will show up indicating that a socket is already listening on the specified port:
[emerg]: bind() to 0.0.0.0:80 failed (98: Address already in use) […] [emerg]: still could not bind().
Beyond this point, you may control the daemon by stopping it, restarting it, or simply reloading its configuration. Controlling is done by sending signals to the process using the
nginx -s command.
Stops the daemon immediately (using the
Stops the daemon gracefully (using the
Reopens the log files.
Reloads the configuration.
Note that when starting the daemon, stopping it, or performing any of the preceding operations, the configuration file is first parsed and verified. If the configuration is invalid, whatever command you have submitted will fail, even when trying to stop the daemon. In other words, in some cases you will not be able to even stop Nginx if the configuration file is invalid.
An alternate way to terminate the process, in desperate cases only, is to use the
killall commands with root privileges:
[firstname.lastname@example.org ~]# killall nginx
As you can imagine, testing the validity of your configuration will become crucial if you constantly tweak your server setup . The slightest mistake in any of the configuration files can result in a loss of control over the service—you will then be unable to stop it via regular
init control commands, and obviously, it will refuse to start again.
Consequently, the following command will be useful to you in many occasions; it allows you to check the syntax, validity, and integrity of your configuration:
[email@example.com ~]$ /usr/local/nginx/sbin/nginx –t
–t switch stands for test configuration. Nginx will parse the configuration anew and let you know whether it is valid or not. A valid configuration file does not necessarily mean Nginx will start, though, as there might be additional problems such as socket issues, invalid paths, or incorrect access permissions.
Obviously, manipulating your configuration files while your server is in production is a dangerous thing to do and should be avoided when possible. The best practice, in this case, is to place your new configuration into a separate temporary file and run the test on that file. Nginx makes it possible by offering the
[firstname.lastname@example.org sbin]$ ./nginx –t –c /home/alex/test.conf
This command will parse
/home/alex/test.conf and make sure it is a valid Nginx configuration file. When you are done, after making sure that your new file is valid, proceed to replacing your current configuration file and reload the server configuration:
[email@example.com sbin]$ cp -i /home/alex/test.conf /usr/local/nginx/conf/nginx.conf cp: erase 'nginx.conf' ? yes [firstname.lastname@example.org sbin]$ ./nginx –s reload
Another switch that might come in handy in many situations is
–V. Not only does it tell you the current Nginx build version, but more importantly, it also reminds you about the arguments that you used during the configuration step—in other words, the command switches that you passed to the
configure script before compilation.
[email@example.com sbin]$ ./nginx -V nginx version: nginx/1.8.0 (Ubuntu) built by gcc 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04) TLS SNI support enabled configure arguments: --with-http_ssl_module
In this case, Nginx was configured with the
--with-http_ssl_module switch only.
Why is this so important? Well, if you ever try to use a module that was not included with the
configure script during the precompilation process, the directive enabling the module will result in a configuration error. Your first reaction will be to wonder where the syntax error comes from. Your second reaction will be to wonder if you even built the module in the first place! Running
nginx –V will answer this question.
–g option lets you specify additional configuration directives in case they were not included in the configuration file:
[firstname.lastname@example.org sbin]$ ./nginx –g "timer_resolution 200ms";
In this section, we will create a script that will transform the Nginx daemon into an actual system service. This will result mainly in two outcomes: the daemon will be controllable using standard commands, and more importantly, it will be launched automatically on system startup and stopped on system shutdown.
Most Linux-based operating systems to date use a System-V style init daemon. In other words, their startup process is managed by a daemon called
init, which functions in a way that is inherited from the old System V Unix-based operating system.
This daemon functions on the principle of runlevels, which represent the state of the computer. Here is a table representing the various runlevels and their signification:
System is halted
Single-user mode (rescue mode)
Multiuser mode, without NFS support
Full multiuser mode
Graphical interface mode
You can manually initiate a runlevel transition: use the
telinit 0 command to shut down your computer or
telinit 6 to reboot it.
For each runlevel transition, a set of services are executed. This is the key concept to understand here: when your computer is stopped, its runlevel is 0. When you turn it on, there will be a transition from runlevel 0 to the default computer startup runlevel. The default startup runlevel is defined by your own system configuration (in the
/etc/inittab file), and the default value depends on the distribution you are using. Debian and Ubuntu use runlevel 2, Red Hat and Fedora use runlevel 3 or 5, CentOS and Gentoo use runlevel 3, and so on—the list is long.
So, in summary, when you start your computer running CentOS, it operates a transition from runlevel 0 to runlevel 3. That transition consists of starting all services that are scheduled for runlevel 3. The question that remains is how to schedule a service to be started at a specific runlevel.
For each runlevel, there is a directory containing scripts to be executed. If you enter these directories (
rc6.d), you will not find actual files, but rather symbolic links referring to scripts located in the
init.d directory. Service startup scripts will indeed be placed in
init.d, and links will be created by tools placing them in the proper directories.
init script, also known as a service startup script or even sysv script, is a shell script respecting a certain standard. The script controls a daemon application by responding to commands such as
stop, and others, which are triggered at two levels. First, when the computer starts, if the service is scheduled to be started for the system runlevel, the
init daemon will run the script with the
start argument. The other possibility for you is to manually execute the script by calling it from the shell:
[email@example.com ~]# service httpd start
Or if your system does not come with the
[firstname.lastname@example.org ~]# /etc/init.d/httpd start
The script must accept at least the
status commands, as they will be used by the system to respectively start up, shut down, restart, forcefully reload the service, or inquire its status. However, to enlarge your field of action as a system administrator, it is often interesting to provide further options, such as a
reload argument to reload the service configuration or a
try-restart argument to stop and start the service again.
Note that since
service httpd start and
/etc/init.d/httpd start essentially do the same thing, with the exception that the second command will work on all operating systems, we will make no further mention of the
service command and will exclusively use the
We will thus create a shell script to start and stop our Nginx daemon and also to restart and reload it. The purpose here is not to discuss Linux shell script programming, so we will merely provide the source code of an existing
init script, along with some comments to help you understand it.
Due to differences in the format of the
init scripts from one distribution to another, we will discover two separate scripts here. The first one is meant for Debian-based distributions such as Debian, Ubuntu, Knoppix, and so forth.
First, create a file called
nginx with the text editor of your choice, and save it in the
/etc/init.d/ directory (on some systems,
/etc/init.d/ is actually a symbolic link to
/etc/rc.d/init.d/). In the file you just created, insert the script provided in the code bundle supplied with this book. Make sure that you change the paths to make them correspond to your actual setup.
You will need root permissions to save the script into the
Due to the system tools, shell programming functions, and specific formatting that it requires, the preceding script is only compatible with Debian-based distributions. If your server is operated by a Red Hat–based distribution such as CentOS, Fedora, and many more, you will need an entirely different script.
Placing the file in the
init.d directory does not complete our work. There are additional steps that will be required to enable the service. First, make the script executable. So far, it is only a piece of text that the system refuses to run. Granting executable permissions on the script is done with the
[email@example.com ~]# chmod +x /etc/init.d/nginx
Note that if you created the file as the root user, you will need to be logged in as root to change the file permissions.
At this point, you should already be able to start the service using
service nginx start or
/etc/init.d/nginx start, as well as stopping, restarting, or reloading the service.
The last step here will be to make it so the script is automatically started at the proper runlevels. Unfortunately, doing this entirely depends on what operating system you are using. We will cover the two most popular families—Debian, Ubuntu, or other Debian-based distributions and Red Hat/Fedora/CentOS, or other Red Hat–derived systems.
For the Debian-based distribution, a simple command will enable the
init script for the system runlevel:
[firstname.lastname@example.org ~]# update-rc.d -f nginx defaults
This command will create links in the default system
runlevel folders. For the reboot and shutdown runlevels, the script will be executed with the
stop argument; for all other runlevels, the script will be executed with
start. You can now restart your system and see your Nginx service being launched during the boot sequence.
For the Red Hat–based systems family, the command differs, but you get an additional tool to manage system startup. Adding the service can be done via the following command:
[email@example.com ~]# chkconfig nginx on
Once that is done, you can then verify the runlevels for the service:
[firstname.lastname@example.org ~]# chkconfig --list nginx Nginx 0:off 1:off 2:on 3:off 4:on 5:on 6:off
Another tool will be useful to you to manage system services, namely,
ntsysv. It lists all services scheduled to be executed on system startup and allows you to enable or disable them at will.
Note that prior to using
ntsysv, you must first run the
chkconfig nginx on command, otherwise Nginx will not appear in the list of services.
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed to you directly.
Since mid-2013, NGINX, Inc., the company behind the Nginx project, also offers a paid subscription called NGINX Plus. The announcement came as a surprise for the open source community, but several companies quickly jumped on the bandwagon and reported amazing improvements in terms of performance and scalability after using NGINX Plus.
NGINX, Inc., the high performance web company, today announced the availability of NGINX Plus, a fully-supported version of the popular NGINX open source software complete with advanced features and offered with professional services. The product is developed and supported by the core engineering team at Nginx Inc., and is available immediately on a subscription basis.
As business requirements continue to evolve rapidly, such as the shift to mobile and the explosion of dynamic content on the Web, CIOs are continuously looking for opportunities to increase application performance and development agility, while reducing dependencies on their infrastructure. NGINX Plus provides a flexible, scalable, uniformly applicable solution that was purpose built for these modern, distributed application architectures.
Considering the pricing plans ($1,500 per year per instance) and the additional features made available, this platform is indeed clearly aimed at large corporations looking to integrate Nginx into their global architecture seamlessly and effortlessly. Professional support from the Nginx team is included and discounts can be offered for multiple-instance subscriptions. This book covers the open source version of Nginx only and does not detail advanced functionality offered by NGINX Plus. For more information about the paid subscription, take a look at http://www.nginx.com.
This chapter covered a number of critical steps. You first made sure that your system contained all the required components for compiling Nginx. You then proceeded to select the proper version branch for your usage—will you be using the stable version or a more advanced, yet potentially less stable, one? After downloading the source and configuring the compilation process by enabling or disabling features and modules such as SSL, GeoIP, and more, you compiled the application and installed it on the system in the directory of your choice. You created an init script and modified the system boot sequence to schedule for the service to be started.
From this point on, Nginx is installed on your server and automatically starts with the system. Your web server is functional, though it does not yet answer the most basic functionality: serving a website. The first step towards hosting a website will be to prepare a suitable configuration file. The next chapter will cover the basic configuration of Nginx and will teach you how to optimize performance based on the expected audience and system resources.