How to Install Nginx on Ubuntu, CentOS and From Source Code

Nginx (pronounced "engine-x") is a free, open-source web server that has grown tremendously in popularity over the past decade. Created by Igor Sysoev in 2002, Nginx now powers over 30% of all active websites – more than the next two competitors (Apache and Microsoft IIS) combined.

So what makes Nginx so popular? It‘s known for having a very lightweight and high-performance architecture that can easily handle tens of thousands of concurrent connections with minimal resource usage. Nginx leverages asynchronous, event-driven processing for top speed and scalability.

In this comprehensive guide, you‘ll learn multiple methods for installing Nginx on Ubuntu, CentOS or RHEL servers. We‘ll cover:

  • Installing from distro repositories
  • Compiling and installing from source code
  • Post-installation configuration tips
  • Securing, optimizing and managing Nginx
  • Upgrading or downgrading versions
  • Troubleshooting common issues

Whether you‘re setting up your first Nginx server or migrating from another platform like Apache, you‘ll find all the information needed here. Let‘s get started!

Prerequisites

Before installing Nginx, make sure your system meets the minimum requirements:

OS Version

  • Ubuntu 16.04 or higher
  • CentOS/RHEL 7 or higher

Hardware

  • 1 GHz CPU with 1 GB RAM for basic install
  • 2 GHz multi-core CPU with 2+ GB for high-traffic sites

Dependencies

  • PCRE, zlib, and OpenSSL libraries
  • GCC compiler needed to build from source

Okay, with the prerequisites out of the way, let‘s move on to installing Nginx on Ubuntu and CentOS using the distro repositories.

Installing Nginx on Ubuntu

Ubuntu has official Nginx packages available in its default repositories. Here‘s how to install Nginx on Ubuntu 16.04/18.04/20.04 LTS:

First, update the package index:

sudo apt update

Next, install Nginx along with its companion packages:

sudo apt install nginx nginx-common nginx-full

The main package is nginx which installs a barebones server with default modules. nginx-common has common configuration files and scripts, while nginx-full includes a wider array of useful third-party modules.

Configure Firewall

Assuming you have UFW firewall enabled, allow HTTP and HTTPS access:

sudo ufw allow ‘Nginx Full‘

This opens ports 80 and 443 for all connections. Restrict access further as per your specific requirements.

Verify the Installation

Check that Nginx is up and running:

systemctl status nginx

You should see an active (running) status. Test it locally:

curl -I http://localhost

This makes an HTTP request to the Nginx welcome page listening on the loopback interface. You should get a successful response header, confirming Nginx was installed properly.

Troubleshooting Tips

If you ran into any errors like packages not found or service not starting, here are some things to check:

  • Make sure your Ubuntu version is 16.04 or above
  • Run apt update and try install again
  • Check if UFW is blocking traffic on ports 80/443
  • Look at logs in /var/log/nginx/ and /var/log/syslog for clues

Okay, that wraps up installing and setting up basic Nginx functionality on Ubuntu! Next, we‘ll tackle CentOS/RHEL installs using yum.

Installing Nginx on CentOS and RHEL

Nginx packages for CentOS and RHEL are provided by the EPEL repository.

Let‘s begin by installing the Extra Packages for Enterprise Linux (EPEL) on CentOS or RHEL servers:

sudo yum install epel-release

Now install Nginx:

sudo yum install nginx

This will install Nginx along with the nginx-module-xslt and nginx-module-geoip extension modules.

Configure SELinux

On RHEL and CentOS 7+, make sure SELinux is not blocking Nginx:

sudo setsebool -P httpd_can_network_connect=1

Verify the Installation

Start the Nginx service:

sudo systemctl start nginx

Check the status:

sudo systemctl status nginx

Test that it‘s responding on port 80:

curl -I http://localhost

You should get a similar 200 status response as the Ubuntu example.

Troubleshooting Tips

Here are some common install issues and fixes:

  • If you get 404 errors, check SELinux rules with sudo semanage port -l | grep http
  • Look in /var/log/audit/audit.log for access denial messages
  • Enable EPEL repo again with yum reinstall epel-release
  • Package conflicts can occur if you already have httpd installed

This concludes setting up Nginx on CentOS or RHEL systems using repository packages!

Next, we‘ll go through the process of compiling and installing Nginx from source code.

Compiling and Install Nginx from Source

Installing Nginx from the source code allows you to customize the compiling options as per your requirements. It also lets you choose the installation directory.

Some reasons why you might want to compile from source instead of using repository packages:

  • Create a minimal installation with only required modules
  • Enable non-standard modules like HTTP push or RTMP
  • Install experimental module versions for testing
  • Customize installation prefixes and directories
  • Build for multiple architectures from same source

Let‘s go through the build process step-by-step:

Step 1: Install Build Tools & Dependencies

To compile anything from source, we need essential build tools like gcc and make, as well as Nginx dependencies like OpenSSL:

sudo yum install gcc gcc-c++ make  \
                zlib zlib-devel \
                pcre pcre-devel \
                openssl openssl-devel

Step 2: Download and Extract Source

Go to Nginx download page and grab the latest stable release. At time of writing, it is nginx-1.14.0.

wget http://nginx.org/download/nginx-1.14.0.tar.gz
tar -xvzf nginx-1.14.0.tar.gz

This will extract the source tarball into a folder nginx-1.14.0

Step 3: Configure Options & Make

Go into the extracted source directory and run the configure script with your chosen options:

cd nginx-1.14.0
./configure --prefix=/etc/nginx \
            --sbin-path=/usr/sbin/nginx \
            --conf-path=/etc/nginx/nginx.conf \          
            --error-log-path=/var/log/nginx/error.log \
            --http-log-path=/var/log/nginx/access.log \                  
            --pid-path=/var/run/nginx/nginx.pid \               
            --lock-path=/var/lock/nginx.lock \
            --user=nginx --group=nginx \
            --with-http_ssl_module 

This sets up the install directories and enables HTTPS support. Customize based on your needs.

Finally, build and install the binaries:

make 
sudo make install

Step 4: Set Up Init Scripts

For easy service management, configure the Nginx init scripts:

CentOS 6:

sudo vi /etc/init.d/nginx

CentOS 7+:

sudo vi /usr/lib/systemd/system/nginx.service

Adjust based on the paths we set earlier. Test-start the service now.

Step 5: Verify Installation

sudo systemctl start nginx
curl -I http://localhost

You should get a 200 OK response again, confirming Nginx built properly and is now serving traffic.

And that‘s it! You have Nginx up from source on Enterprise Linux. Tweak the parameters further to suit your environment.

With Nginx installed, let‘s move on to some recommended post-configuration steps.

Post-Installation Configuration

After installing Nginx either from repositories or compiling from source, there are some additional recommended steps:

Understand the Directory Structure

Nginx has following main subdirectories:

  • /etc/nginx – Global config files
  • /usr/share/nginx – Default static assets
  • /var/log/nginx – Access and error logs
  • /var/lib/nginx – Persistent data like cache

Edit Configuration Files

The main config file is /etc/nginx/nginx.conf. Go through all the settings here and be sure to understand each one fully. Make tweaks according to your server environment.

Some directives to adjust:

  • worker_processes – Number of CPU cores to use
  • error_log and access_log paths
  • Web root directory on server blocks

Optimize OS Limits

For high loads, increase system resource limits for Nginx in /etc/security/limits.conf:

nginx soft nofile 65536
nginx hard nofile 65536

This raises the open file handles limit per process to 64K which improves capacity.

Secure Nginx

Refer our Nginx security guide for tightening access controls via firewall policies, TLS encryption, restricting locations, limiting modules and more.

Okay, Nginx should now be hardened for production use cases!

Managing the Nginx Service

Let‘s go through some useful commands for controlling the Nginx processes:

Start Nginx

sudo systemctl start nginx

Stop Nginx

sudo systemctl stop nginx

Reload Config

sudo systemctl reload nginx

This applies configuration changes dynamically without dropping any connections.

Config Validation

/usr/sbin/nginx -t

Test syntax of config files before reloading them.

Graceful Shutdown

sudo kill -s QUIT $(cat /run/nginx.pid)

Send SIGQUIT to safely finish pending requests before stopping.

Log Rotation

To prevent log files from getting too large, set up daily log rotation:

sudo cp /etc/logrotate.d/nginx /etc/logrotate.d/nginx-custom
sudo vi /etc/logrotate.d/nginx-custom

Configure with your chosen rotation frequency and retention cycle.

And that covers some essential service management tasks! Now let‘s look at upgrading Nginx smoothly.

Upgrading Nginx

As with any server software, it‘s good practice to keep Nginx updated to the latest stable versions. New releases provide security patches, bug fixes, performance improvements and new features.

Before upgrading consider the following:

  • Review release notes for any incompatible changes
  • Backup existing config files & sites
  • Test upgrade on staging server first
  • Schedule a maintenance window

To upgrade Nginx package installs:

sudo apt update 
sudo apt install nginx

OR:

sudo yum update nginx

This will fetch latest versions from the repositories.

To upgrade Nginx source installs:

wget http://nginx.org/download/nginx-1.16.0.tar.gz 
tar -xvzf nginx-1.16.0.tar.gz
cd nginx-1.16.0
./configure --prefix=/etc/nginx [plus original options]
make
make upgrade

The key thing here is using the upgrade instead of install for source builds – this replaces the old binary. Restart Nginx to load the new version. Monitor system health post upgrade.

To downgrade to a previous version, simply install the older package or recompile from the desired release source tarball.

Conclusion

Congratulations! You now have Nginx fully up and running on your Ubuntu or CentOS systems.

To recap, we covered installing Nginx from distro repositories as well as building and compiling manually from source code for maximum customization.

You should also have a good understanding of critical post-deployment steps like configuring logs, securing Nginx, managing the service for high availability, and safely upgrading versions.

Nginx is a very lightweight, flexible and scalable platform that excels as a high-performance web server, reverse proxy or load balancer. Have fun deploying fast and reliable applications with it!

For further learning, check out Nginx‘s excellent official documentation and community forum.

Tags: