AlmaLinuxRHEL Based

How To Install OpenResty on AlmaLinux 10

Install OpenResty on AlmaLinux 10

OpenResty represents a powerful fusion of NGINX’s robust web server capabilities with the dynamic scripting potential of LuaJIT. This comprehensive guide will walk you through installing OpenResty on AlmaLinux 10, providing you with the knowledge to harness this exceptional web platform for modern applications.

As enterprises increasingly demand high-performance web solutions, OpenResty emerges as a compelling choice for developers and system administrators. Built upon NGINX’s proven architecture, OpenResty extends functionality through embedded Lua scripting, enabling dynamic content generation and complex application logic directly within the web server layer.

AlmaLinux 10, as a community-driven, enterprise-grade Linux distribution, provides an ideal foundation for OpenResty deployment. The compatibility between these technologies ensures stable, scalable web infrastructure suitable for production environments.

What is OpenResty and Why Choose It on AlmaLinux 10

OpenResty transforms traditional web server functionality by integrating NGINX with LuaJIT, creating a comprehensive web application platform. Unlike conventional web servers that merely serve static content or proxy requests, OpenResty enables developers to implement complex business logic directly within the server configuration.

The platform includes carefully selected NGINX modules and Lua libraries designed for enhanced web application hosting. These components work together seamlessly, providing non-blocking interactions with databases like Redis, PostgreSQL, MySQL, and Memcached. This architecture significantly improves application performance by reducing the overhead typically associated with separate application server layers.

AlmaLinux 10 offers several advantages as the hosting environment for OpenResty. The distribution maintains binary compatibility with Red Hat Enterprise Linux while providing long-term stability and security updates. This combination ensures that your OpenResty installation remains secure and maintainable throughout its operational lifecycle.

The synergy between OpenResty and AlmaLinux 10 becomes particularly evident in enterprise environments where reliability, performance, and maintainability are paramount. Organizations benefit from reduced infrastructure complexity while maintaining the flexibility to implement sophisticated web application features.

Prerequisites and System Requirements

Before proceeding with OpenResty installation, ensure your AlmaLinux 10 system meets the necessary requirements. A minimum of 1GB RAM is recommended for basic installations, though production environments typically require 2GB or more depending on expected traffic volumes.

Your system requires sudo privileges for package installation and service management. Network connectivity is essential for downloading packages from OpenResty repositories and installing dependencies. Verify your AlmaLinux 10 version using the command cat /etc/os-release to confirm compatibility.

If existing web servers like NGINX or Apache are running, stop and disable them to prevent port conflicts:

sudo systemctl stop nginx apache2
sudo systemctl disable nginx apache2

Update your system packages to ensure compatibility with OpenResty components:

sudo dnf update -y

Install essential development tools and dependencies that may be required during the installation process:

sudo dnf groupinstall "Development Tools" -y
sudo dnf install wget curl gnupg2 -y

Understanding OpenResty Installation Methods

OpenResty installation on AlmaLinux 10 can be accomplished through multiple approaches, each offering distinct advantages depending on your specific requirements and environment constraints.

The package manager method represents the recommended approach for most users. This method leverages pre-compiled binary packages optimized for RHEL-compatible distributions, ensuring compatibility and simplified maintenance. Package installation provides automatic dependency resolution and integrates seamlessly with system update mechanisms.

Source compilation offers maximum flexibility for advanced users requiring custom configurations or specific module integrations. While more complex, building from source allows fine-tuned optimization and inclusion of third-party modules not available in standard packages.

Container deployment using Docker provides isolation and portability benefits, particularly valuable in microservices architectures or development environments requiring consistent deployments across different systems.

Method 1: Installing via Package Manager (Recommended)

Adding the OpenResty Repository

The package manager installation begins by adding the official OpenResty repository to your AlmaLinux 10 system. This approach ensures access to the latest stable releases and security updates.

First, install the wget utility if not already available:

sudo dnf install wget -y

Download the OpenResty repository configuration file specifically designed for RHEL-compatible systems:

wget https://openresty.org/package/centos/openresty.repo

Move the repository file to the appropriate system directory:

sudo mv openresty.repo /etc/yum.repos.d/

Update the package manager index to recognize the newly added repository:

sudo dnf check-update

This process configures your system to access OpenResty packages directly from the official repository, ensuring authenticity and compatibility with your AlmaLinux 10 installation.

Installing OpenResty Core Package

With the repository configured, proceed to install the main OpenResty package:

sudo dnf install openresty -y

The installation process automatically resolves dependencies and configures the necessary system components. Monitor the installation output for any errors or warnings that may require attention.

Verify the successful installation by checking the OpenResty executable location:

which openresty

This command should return /usr/local/openresty/nginx/sbin/openresty, confirming proper installation.

Check the installed version to ensure you have the latest release:

openresty -V

The version output provides detailed information about compiled modules and configuration options, useful for troubleshooting and optimization planning.

Installing Additional Utilities

Enhance your OpenResty installation with supplementary utilities that extend functionality and improve development productivity.

Install the resty command-line utility for Lua script execution and testing:

sudo dnf install openresty-resty -y

The resty utility enables direct execution of Lua scripts, facilitating development and debugging processes.

Install the OpenResty Package Manager (OPM) for third-party module management:

sudo dnf install openresty-opm -y

OPM simplifies the process of installing community-contributed Lua modules, expanding OpenResty’s capabilities beyond standard offerings.

Install documentation utilities for offline reference:

sudo dnf install openresty-doc -y

These utilities provide comprehensive documentation access through the restydoc command, valuable for development and troubleshooting scenarios.

Method 2: Building from Source

Downloading Source Code

Advanced users requiring custom configurations or specific module integrations may prefer building OpenResty from source code. This method provides maximum control over the compilation process and enables inclusion of specialized components.

Download the latest OpenResty source tarball from the official website:

wget https://openresty.org/download/openresty-1.27.1.1.tar.gz

Extract the archive to begin the compilation process:

tar -zxvf openresty-1.27.1.1.tar.gz
cd openresty-1.27.1.1/

Review the available configuration options:

./configure --help

This command displays comprehensive configuration options, enabling customization of the build process according to specific requirements.

Compilation Process

Configure the build process with desired options. A basic configuration suitable for most environments:

./configure --prefix=/usr/local/openresty \
    --with-luajit \
    --with-http_ssl_module \
    --with-http_realip_module \
    --with-http_stub_status_module

Compile the source code using multiple CPU cores for improved performance:

make -j$(nproc)

The compilation process may take several minutes depending on system specifications and selected options.

Install the compiled binaries:

sudo make install

Custom Build Options

Source compilation enables integration of custom OpenSSL and PCRE libraries for enhanced security and performance. Download and prepare these dependencies before configuring OpenResty:

wget https://github.com/openssl/openssl/releases/download/openssl-3.5.0/openssl-3.5.0.tar.gz
tar -zxvf openssl-3.5.0.tar.gz

wget https://github.com/PCRE2Project/pcre2/releases/download/pcre2-10.45/pcre2-10.45.tar.gz
tar -zxvf pcre2-10.45.tar.gz

Configure OpenResty with custom dependencies:

./configure --with-openssl=../openssl-3.5.0 \
    --with-pcre=../pcre2-10.45 \
    --with-http_ssl_module \
    -j4

This approach ensures optimal compatibility and performance tuning for specific deployment requirements.

Initial Configuration and Setup

Understanding Configuration Structure

OpenResty inherits NGINX’s configuration structure while extending it with Lua scripting capabilities. The primary configuration file location depends on your installation method.

For package installations, the configuration resides at:

  • /usr/local/openresty/nginx/conf/nginx.conf

For source installations, the location may vary based on the prefix specified during compilation.

Create a backup of the default configuration before making modifications:

sudo cp /usr/local/openresty/nginx/conf/nginx.conf /usr/local/openresty/nginx/conf/nginx.conf.backup

Basic Configuration Setup

Replace the default configuration with a basic setup optimized for OpenResty functionality:

worker_processes auto;
error_log /var/log/openresty/error.log;
pid /var/run/openresty.pid;

events {
    worker_connections 1024;
    use epoll;
}

http {
    include       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/openresty/access.log main;
    
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    
    server {
        listen 80 default_server;
        listen [::]:80 default_server;
        server_name localhost;
        root /usr/local/openresty/nginx/html;
        index index.html index.htm;
        
        location / {
            try_files $uri $uri/ =404;
        }
        
        location /lua-test {
            default_type text/html;
            content_by_lua_block {
                ngx.say('<h1>OpenResty Lua Test</h1>')
                ngx.say('<p>Current time: ', os.date(), '</p>')
            }
        }
        
        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
            root /usr/local/openresty/nginx/html;
        }
    }
}

Service Management

Configure OpenResty as a system service for automatic startup and management. Create a systemd service file:

sudo tee /etc/systemd/system/openresty.service << 'EOF'
[Unit]
Description=The OpenResty Application Platform
After=syslog.target network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=/var/run/openresty.pid
ExecStartPre=/usr/local/openresty/nginx/sbin/nginx -t
ExecStart=/usr/local/openresty/nginx/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
KillMode=mixed
KillSignal=SIGQUIT
TimeoutStopSec=5
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF

Enable and start the OpenResty service:

sudo systemctl daemon-reload
sudo systemctl enable openresty
sudo systemctl start openresty

Testing Your OpenResty Installation

Basic Functionality Tests

Verify OpenResty is running correctly by checking the service status:

sudo systemctl status openresty

A successful installation displays an active (running) status with no error messages.

Test the default web page using curl:

curl http://localhost/

This command should return the default OpenResty welcome page HTML content.

Verify process status and port binding:

ps aux | grep nginx
netstat -tulpn | grep :80

These commands confirm that OpenResty processes are running and listening on the expected port.

Lua Integration Testing

Test Lua scripting functionality by accessing the configured test endpoint:

curl http://localhost/lua-test

The response should display HTML content generated by the Lua script, demonstrating successful integration between NGINX and LuaJIT components.

Create a more comprehensive Lua test by adding a new location block to your configuration:

location /api-test {
    default_type application/json;
    content_by_lua_block {
        local cjson = require "cjson"
        local data = {
            status = "success",
            message = "OpenResty API test",
            timestamp = ngx.time(),
            server = "AlmaLinux 10"
        }
        ngx.say(cjson.encode(data))
    }
}

Test the API endpoint:

curl -H "Accept: application/json" http://localhost/api-test

Performance Verification

Monitor resource usage during basic load testing to ensure optimal performance:

top -p $(pgrep nginx)

Use simple load testing tools to verify OpenResty handles concurrent connections effectively:

ab -n 1000 -c 10 http://localhost/

Review log files for any errors or warnings:

sudo tail -f /var/log/openresty/error.log
sudo tail -f /var/log/openresty/access.log

Advanced Configuration Options

Performance Tuning

Optimize OpenResty performance for production environments by adjusting worker processes and connection handling:

worker_processes auto;
worker_rlimit_nofile 65535;

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

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 30;
    keepalive_requests 100;
    
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
}

Configure SSL/TLS for secure communications:

server {
    listen 443 ssl http2;
    server_name your-domain.com;
    
    ssl_certificate /path/to/certificate.crt;
    ssl_certificate_key /path/to/private.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512;
    ssl_prefer_server_ciphers off;
}

Lua Module Integration

Leverage the OpenResty Package Manager to install additional Lua modules:

sudo opm get pintsized/lua-resty-http
sudo opm get openresty/lua-resty-redis
sudo opm get openresty/lua-resty-mysql

Integrate installed modules in your Lua scripts:

location /redis-test {
    content_by_lua_block {
        local redis = require "resty.redis"
        local red = redis:new()
        
        red:set_timeouts(1000, 1000, 1000)
        
        local ok, err = red:connect("127.0.0.1", 6379)
        if not ok then
            ngx.say("Failed to connect: ", err)
            return
        end
        
        local res, err = red:set("test_key", "Hello from OpenResty")
        if not res then
            ngx.say("Failed to set key: ", err)
            return
        end
        
        ngx.say("Redis integration successful")
    }
}

Security Hardening

Implement security best practices in your OpenResty configuration:

# Hide version information
server_tokens off;

# Security headers
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

# Rate limiting
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_req zone=api burst=20 nodelay;

# Access control
location /admin {
    allow 192.168.1.0/24;
    deny all;
}

Troubleshooting Common Issues

Installation Errors

Repository connectivity issues may occur due to network restrictions or DNS problems. Verify network connectivity and DNS resolution:

ping openresty.org
nslookup openresty.org

Package dependency conflicts can be resolved by updating the system and clearing package caches:

sudo dnf clean all
sudo dnf update -y

Permission-related problems often stem from insufficient privileges. Ensure you have sudo access and proper file permissions:

sudo chown -R openresty:openresty /usr/local/openresty/
sudo chmod -R 755 /usr/local/openresty/nginx/

Configuration Issues

Syntax errors in nginx.conf prevent OpenResty from starting. Test configuration validity:

sudo openresty -t

This command identifies syntax errors and provides specific line numbers for correction.

Port binding conflicts occur when other services use port 80 or 443. Identify conflicting processes:

sudo lsof -i :80
sudo lsof -i :443

Service startup failures often relate to configuration errors or missing dependencies. Check system logs for detailed error information:

sudo journalctl -u openresty.service -f

Performance Problems

High CPU or memory usage may indicate configuration issues or inadequate system resources. Monitor system performance:

htop
iotop

Slow response times can result from suboptimal configuration or network issues. Use profiling tools to identify bottlenecks:

curl -w "@curl-format.txt" -o /dev/null -s http://localhost/

Create a curl format file for detailed timing analysis:

cat > curl-format.txt << 'EOF'
     time_namelookup:  %{time_namelookup}\n
        time_connect:  %{time_connect}\n
     time_appconnect:  %{time_appconnect}\n
    time_pretransfer:  %{time_pretransfer}\n
       time_redirect:  %{time_redirect}\n
  time_starttransfer:  %{time_starttransfer}\n
                     ----------\n
          time_total:  %{time_total}\n
EOF

Security Considerations and Best Practices

Security Updates

Maintain security by regularly updating OpenResty packages and monitoring security advisories from the OpenResty project. Subscribe to security mailing lists and configure automatic updates for critical security patches:

sudo dnf update openresty

Monitor system logs for security-related events and implement log analysis tools for proactive threat detection.

Operational Security

Configure firewall rules to restrict access to necessary ports only:

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

Implement proper user access controls and avoid running OpenResty as root in production environments. Create dedicated users for service management:

sudo useradd -r -s /sbin/nologin openresty

Establish comprehensive backup procedures for configuration files and application data:

sudo tar -czf openresty-backup-$(date +%Y%m%d).tar.gz /usr/local/openresty/nginx/conf/

Maintenance and Updates

Regular Maintenance Tasks

Implement monitoring solutions to track OpenResty performance and system health. Use tools like Prometheus and Grafana for comprehensive monitoring:

# Monitor OpenResty status
curl -s http://localhost/nginx_status

Configure log rotation to prevent disk space issues:

sudo logrotate -d /etc/logrotate.d/openresty

Perform regular configuration backups and test restore procedures to ensure business continuity.

Update Procedures

Test updates in staging environments before applying to production systems. Create staging configurations that mirror production settings:

sudo cp -r /usr/local/openresty/nginx/conf/ /usr/local/openresty/nginx/conf.staging/

Implement rollback procedures for quick recovery from failed updates:

sudo systemctl stop openresty
sudo cp nginx.conf.backup nginx.conf
sudo systemctl start openresty

Monitor system performance and error logs after updates to identify potential issues early.

Congratulations! You have successfully installed OpenResty. Thanks for using this tutorial for installing OpenResty on AlmaLinux OS 10 system. For additional help or useful information, we recommend you check the official OpenResty website.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button