BLOG POSTS
How to Install Nginx on CentOS 8

How to Install Nginx on CentOS 8

Nginx (pronounced “engine-x”) is a high-performance web server and reverse proxy that has become the backbone of modern web infrastructure. Installing Nginx on CentOS 8 is a crucial skill for anyone managing Linux servers, especially since CentOS 8 offers excellent stability and performance characteristics. This guide will walk you through multiple installation methods, configuration basics, troubleshooting common issues, and optimization techniques to get your Nginx server running smoothly.

Understanding Nginx Architecture and Benefits

Before diving into installation, it’s worth understanding why Nginx has gained such widespread adoption. Unlike Apache’s process-based architecture, Nginx uses an event-driven, asynchronous architecture that can handle thousands of concurrent connections with minimal memory footprint.

Key advantages include:

  • Low memory usage (typically 1-2MB per worker process)
  • High concurrency support (10,000+ simultaneous connections)
  • Excellent performance for serving static content
  • Built-in load balancing and reverse proxy capabilities
  • Modular architecture with extensive third-party module support
Feature Nginx Apache Lighttpd
Memory Usage Very Low High Low
Concurrent Connections 10,000+ 1,000-2,000 5,000+
Static Content Performance Excellent Good Excellent
Configuration Complexity Moderate Easy Easy

Installation Methods Overview

CentOS 8 offers several ways to install Nginx, each with distinct advantages:

  • DNF Package Manager: Quick and straightforward, includes automatic dependency resolution
  • EPEL Repository: Access to newer versions and additional modules
  • Official Nginx Repository: Latest stable releases directly from Nginx team
  • Source Compilation: Maximum customization and performance optimization

Method 1: Installing Nginx via DNF

The simplest approach uses CentOS 8’s default repositories. First, update your system packages:

sudo dnf update -y

Install Nginx using DNF:

sudo dnf install nginx -y

Start and enable Nginx to run automatically on boot:

sudo systemctl start nginx
sudo systemctl enable nginx

Verify the installation and check status:

sudo systemctl status nginx
nginx -v

Method 2: Using EPEL Repository

EPEL (Extra Packages for Enterprise Linux) often provides newer versions than default repositories. Install EPEL first:

sudo dnf install epel-release -y
sudo dnf update -y

Now install Nginx from EPEL:

sudo dnf install nginx -y

The remaining steps (start, enable, verify) are identical to Method 1.

Method 3: Official Nginx Repository

For the latest stable version with all modules, use the official Nginx repository. Create the repository file:

sudo tee /etc/yum.repos.d/nginx.repo << 'EOF'
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
EOF

Import the GPG key and install:

sudo rpm --import https://nginx.org/keys/nginx_signing.key
sudo dnf install nginx -y

Configuring Firewall and SELinux

CentOS 8 ships with firewalld enabled by default. Open HTTP and HTTPS ports:

sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

For SELinux (Security-Enhanced Linux), ensure Nginx can bind to network ports:

sudo setsebool -P httpd_can_network_connect 1

If you plan to serve content from non-standard directories, set appropriate SELinux contexts:

sudo semanage fcontext -a -t httpd_exec_t "/usr/share/nginx/html(/.*)?"
sudo restorecon -R /usr/share/nginx/html

Basic Nginx Configuration

Understanding Nginx's configuration structure is essential. The main configuration file is located at /etc/nginx/nginx.conf:

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

events {
    worker_connections 1024;
    use epoll;
    multi_accept on;
}

http {
    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;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    include /etc/nginx/conf.d/*.conf;
}

Create a basic server block for your domain:

sudo tee /etc/nginx/conf.d/default.conf << 'EOF'
server {
    listen 80;
    server_name your-domain.com www.your-domain.com;
    root /usr/share/nginx/html;
    index index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }

    location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
}
EOF

Performance Optimization and Tuning

For production environments, several optimizations can significantly improve performance:

# Add to /etc/nginx/nginx.conf in http block
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json;

# Buffer optimization
client_body_buffer_size 10K;
client_header_buffer_size 1k;
client_max_body_size 8m;
large_client_header_buffers 4 4k;

# Timeouts
client_body_timeout 12;
client_header_timeout 12;
keepalive_timeout 15;
send_timeout 10;

# Worker process optimization
worker_processes auto;
worker_rlimit_nofile 65535;

Common Issues and Troubleshooting

Several issues frequently occur during Nginx installation and configuration:

  • Permission Denied Errors: Usually caused by SELinux policies or incorrect file permissions
  • Port Already in Use: Another service (often Apache) is already using port 80
  • Configuration Syntax Errors: Always test configuration before reloading
  • SSL Certificate Issues: Common when setting up HTTPS

Test configuration syntax before applying changes:

sudo nginx -t

Check which process is using port 80:

sudo netstat -tlnp | grep :80
sudo ss -tlnp | grep :80

View detailed error logs:

sudo tail -f /var/log/nginx/error.log

If Nginx fails to start, check system logs:

sudo journalctl -u nginx -f

Real-World Use Cases and Examples

Nginx excels in several scenarios. Here are practical configurations for common use cases:

Reverse Proxy for Node.js Application:

upstream nodejs_backend {
    server 127.0.0.1:3000;
    server 127.0.0.1:3001;
    server 127.0.0.1:3002;
}

server {
    listen 80;
    server_name api.yoursite.com;

    location / {
        proxy_pass http://nodejs_backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
    }
}

Load Balancer Configuration:

upstream backend_servers {
    least_conn;
    server 192.168.1.10:80 weight=3;
    server 192.168.1.11:80 weight=2;
    server 192.168.1.12:80 weight=1 backup;
}

server {
    listen 80;
    server_name loadbalancer.example.com;

    location / {
        proxy_pass http://backend_servers;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

Security Best Practices

Implementing security measures is crucial for production deployments:

# Hide Nginx version
server_tokens off;

# Security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;

# Rate limiting
limit_req_zone $binary_remote_addr zone=login:10m rate=10r/m;

server {
    location /login {
        limit_req zone=login burst=20 nodelay;
        # ... rest of configuration
    }
}

Integration with MangoHost Infrastructure

When deploying Nginx on VPS or dedicated servers, consider these additional optimizations:

  • Adjust worker_processes based on available CPU cores
  • Configure appropriate worker_connections for your server's RAM
  • Implement SSL/TLS termination for HTTPS traffic
  • Set up log rotation to manage disk space effectively

For high-traffic applications, consider implementing Nginx caching:

http {
    proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g 
                     inactive=60m use_temp_path=off;

    server {
        location / {
            proxy_cache my_cache;
            proxy_cache_revalidate on;
            proxy_cache_min_uses 3;
            proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
            proxy_cache_background_update on;
            proxy_cache_lock on;
            
            proxy_pass http://backend;
        }
    }
}

Remember to regularly update Nginx and monitor your server performance. The official Nginx documentation provides comprehensive information about advanced configurations and modules. For additional performance monitoring, consider integrating tools like Prometheus with the Nginx Prometheus Exporter.

With Nginx properly installed and configured on CentOS 8, you'll have a robust, high-performance web server capable of handling significant traffic loads while maintaining excellent resource efficiency.



This article incorporates information and material from various online sources. We acknowledge and appreciate the work of all original authors, publishers, and websites. While every effort has been made to appropriately credit the source material, any unintentional oversight or omission does not constitute a copyright infringement. All trademarks, logos, and images mentioned are the property of their respective owners. If you believe that any content used in this article infringes upon your copyright, please contact us immediately for review and prompt action.

This article is intended for informational and educational purposes only and does not infringe on the rights of the copyright owners. If any copyrighted material has been used without proper credit or in violation of copyright laws, it is unintentional and we will rectify it promptly upon notification. Please note that the republishing, redistribution, or reproduction of part or all of the contents in any form is prohibited without express written permission from the author and website owner. For permissions or further inquiries, please contact us.

Leave a reply

Your email address will not be published. Required fields are marked