强曰为道
与天地相似,故不违。知周乎万物,而道济天下,故不过。旁行而不流,乐天知命,故不忧.
文档目录

OpenResty 高性能网关开发教程 / 第 02 章 - 安装与环境搭建

第 02 章 - 安装与环境搭建

2.1 安装方式概览

方式 适用场景 优点 缺点
包管理器 开发、测试环境 简单快速 版本可能滞后
编译安装 生产环境、定制模块 完全控制 步骤较多
Docker CI/CD、容器化部署 环境一致 需了解 Docker
源码 + luajit2 深度定制 最大灵活度 复杂度高

2.2 包管理器安装(推荐入门)

Ubuntu / Debian

# 安装前置依赖
sudo apt-get update
sudo apt-get install -y wget gnupg ca-certificates lsb-release

# 添加 OpenResty 官方 APT 仓库
wget -O - https://openresty.org/package/pubkey.gpg | sudo gpg --dearmor -o /usr/share/keyrings/openresty.gpg

echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/openresty.gpg] \
  http://openresty.org/package/ubuntu $(lsb_release -sc) main" \
  | sudo tee /etc/apt/sources.list.d/openresty.list

# 安装 OpenResty
sudo apt-get update
sudo apt-get install -y openresty

# 验证安装
/usr/local/openresty/bin/openresty -v

CentOS / RHEL

# 添加 OpenResty 官方 YUM 仓库
sudo yum install -y yum-utils
sudo yum-config-manager --add-repo https://openresty.org/package/centos/openresty.repo

# 安装 OpenResty
sudo yum install -y openresty

# 验证
/usr/local/openresty/bin/openresty -v

macOS

# 使用 Homebrew
brew install openresty/brew/openresty

# 验证
openresty -v

注意:macOS 上的默认路径为 /usr/local/openresty/(Intel)或 /opt/homebrew/openresty/(Apple Silicon)。

2.3 编译安装(推荐生产)

2.3.1 下载源码

# 创建工作目录
mkdir -p ~/openresty-build && cd ~/openresty-build

# 下载 OpenResty 源码(以 1.25.3.2 为例)
wget https://openresty.org/download/openresty-1.25.3.2.tar.gz
tar -xzf openresty-1.25.3.2.tar.gz
cd openresty-1.25.3.2

2.3.2 安装编译依赖

# Ubuntu / Debian
sudo apt-get install -y \
  build-essential \
  libpcre3-dev \
  libssl-dev \
  zlib1g-dev \
  libreadline-dev \
  libncurses5-dev \
  libgd-dev \
  geoip-bin \
  libgeoip-dev

# CentOS / RHEL
sudo yum install -y \
  gcc gcc-c++ make \
  pcre-devel \
  openssl-devel \
  zlib-devel \
  readline-devel \
  ncurses-devel \
  gd-devel \
  GeoIP-devel

2.3.3 配置编译选项

./configure \
  --prefix=/usr/local/openresty \
  --with-pcre-jit \
  --with-http_ssl_module \
  --with-http_realip_module \
  --with-http_stub_status_module \
  --with-http_v2_module \
  --with-http_gzip_static_module \
  --with-http_sub_module \
  --with-http_addition_module \
  --with-http_secure_link_module \
  --with-http_image_filter_module \
  --with-luajit \
  --with-stream \
  --with-stream_ssl_module \
  -j4

常用编译选项说明:

选项 说明
--prefix 安装路径
--with-pcre-jit PCRE JIT 编译,正则性能提升
--with-http_ssl_module HTTPS 支持
--with-http_realip_module 获取客户端真实 IP
--with-http_stub_status_module 监控状态页
--with-http_v2_module HTTP/2 支持
--with-stream TCP/UDP 四层代理
--with-luajit 使用 LuaJIT(默认启用)

2.3.4 编译与安装

make -j$(nproc)
sudo make install

2.3.5 配置环境变量

# 添加到 ~/.bashrc 或 ~/.zshrc
cat >> ~/.bashrc << 'EOF'
export PATH=/usr/local/openresty/bin:/usr/local/openresty/nginx/sbin:$PATH
export OPENRESTY_PREFIX=/usr/local/openresty
EOF

source ~/.bashrc

# 验证
which openresty
openresty -V  # 注意大写 V 查看编译参数

2.4 基本配置文件

2.4.1 目录结构

/usr/local/openresty/
├── bin/                    # 可执行文件
│   ├── openresty           # 启动脚本
│   └── opm                 # 包管理器
├── luajit/                 # LuaJIT 运行时
│   ├── bin/luajit
│   └── lib/
├── lualib/                 # Lua 库目录
│   ├── resty/              # lua-resty 库
│   ├── ngx/                # ngx.* API
│   └── cjson.so            # JSON 库
├── nginx/
│   ├── conf/               # 配置目录
│   │   ├── nginx.conf      # 主配置
│   │   └── mime.types
│   ├── html/               # 默认页面
│   └── logs/               # 日志目录
│       ├── access.log
│       └── error.log
└── pod/                    # OPM 包安装目录

2.4.2 最小配置文件

创建一个干净的配置文件用于开发:

# /usr/local/openresty/nginx/conf/nginx.conf

worker_processes auto;
error_log logs/error.log info;
pid logs/nginx.pid;

events {
    worker_connections 1024;
}

http {
    # 基本 MIME 类型
    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"';

    access_log logs/access.log main;

    # 性能优化
    sendfile        on;
    tcp_nopush      on;
    tcp_nodelay     on;
    keepalive_timeout 65;

    # Lua 模块路径
    lua_package_path "/usr/local/openresty/lualib/?.lua;;";
    lua_package_cpath "/usr/local/openresty/lualib/?.so;;";

    server {
        listen 8080;
        server_name localhost;

        location / {
            default_type text/html;
            content_by_lua_block {
                ngx.say("Hello, OpenResty!")
            }
        }

        # 健康检查端点
        location /health {
            access_log off;
            default_type application/json;
            content_by_lua_block {
                ngx.say('{"status":"ok"}')
            }
        }
    }
}

2.4.3 启动与管理

# 检查配置语法
openresty -t

# 启动
openresty

# 重启(优雅重载配置)
openresty -s reload

# 停止
openresty -s quit   # 优雅停止
openresty -s stop   # 强制停止

# 测试
curl http://localhost:8080/
# 输出: Hello, OpenResty!

2.5 lua-resty 库

lua-resty 是 OpenResty 官方维护的一系列非阻塞 Lua 库,覆盖常用的功能需求:

核心库(随 OpenResty 安装)

库名 说明 用法
resty.http HTTP 客户端 发起非阻塞 HTTP 请求
resty.redis Redis 客户端 操作 Redis
resty.mysql MySQL 客户端 查询 MySQL
resty.md5 MD5 计算 数据摘要
resty.sha1 SHA1 计算 数据摘要
resty.string 字符串工具 hex 编码等
resty.lrucache LRU 缓存 进程内缓存
resty.core 核心 FFI 实现 高性能 API

使用示例:HTTP 客户端

-- /usr/local/openresty/lua/test_http.lua
local http = require "resty.http"

local function fetch_url(url)
    local httpc = http.new()
    httpc:set_timeout(5000)  -- 5 秒超时

    local res, err = httpc:request_uri(url, {
        method = "GET",
        headers = {
            ["User-Agent"] = "OpenResty-Gateway/1.0",
        },
    })

    if not res then
        ngx.log(ngx.ERR, "HTTP request failed: ", err)
        return nil, err
    end

    return {
        status = res.status,
        body   = res.body,
        headers = res.headers,
    }
end

-- 在 content 阶段使用
ngx.say(fetch_url("https://httpbin.org/get").body)

使用示例:Redis 操作

local redis = require "resty.redis"

local function get_redis()
    local red = redis:new()
    red:set_timeout(1000)

    local ok, err = red:connect("127.0.0.1", 6379)
    if not ok then
        ngx.log(ngx.ERR, "Redis connect failed: ", err)
        return nil, err
    end

    -- 可选:认证
    -- local ok, err = red:auth("your_password")

    return red
end

local function close_redis(red)
    -- 放回连接池,而非关闭
    local ok, err = red:set_keepalive(10000, 100)
    if not ok then
        ngx.log(ngx.ERR, "Redis set_keepalive failed: ", err)
    end
end

2.6 OPM 包管理器

OPM(OpenResty Package Manager)是 OpenResty 官方的包管理器,类似 npm 或 pip。

基本使用

# 查看帮助
opm --help

# 搜索包
opm search lua-resty-http

# 安装包(全局)
sudo opm get openresty/lua-resty-http

# 安装到项目目录
opm --install-dir=./deps get openresty/lua-resty-http

# 列出已安装
opm --install-dir=./deps list

# 升级包
sudo opm update openresty/lua-resty-http

常用 OPM 包

包名 说明 安装命令
lua-resty-template HTML 模板引擎 opm get bungle/lua-resty-template
lua-resty-jwt JWT 认证 opm get SkyLothar/lua-resty-jwt
lua-resty-limit-traffic 限流组件 opm get openresty/lua-resty-limit-traffic
lua-resty-healthcheck 健康检查 opm get openresty/lua-resty-healthcheck
lua-resty-consul Consul 客户端 opm Get hamishforbes/lua-resty-consul

注意:在生产环境中,建议将依赖安装到项目目录(--install-dir),避免全局污染。

2.7 验证安装完整性

创建一个综合测试脚本来验证所有组件:

# 添加到 nginx.conf 的 server 块中

location /test-install {
    default_type text/html;
    content_by_lua_block {
        local cjson = require "cjson"
        local http = require "resty.http"

        local result = {
            openresty_version = ngx.var.nginx_version or "unknown",
            lua_version       = jit and jit.version or _VERSION,
            server_time       = ngx.now(),
            worker_pid        = ngx.worker.pid(),
            lua_jit           = jit and "enabled" or "disabled",
        }

        ngx.say(cjson.encode(result))
    }
}
# 测试
curl http://localhost:8080/test-install
# 输出类似: {"openresty_version":"1.25.3.2","lua_version":"LuaJIT 2.1","server_time":1704067200,"worker_pid":12345,"lua_jit":"enabled"}

2.8 常见安装问题

问题 原因 解决方案
nginx: [emerg] unknown directive "lua_code_cache" 编译时未包含 ngx_lua 模块 重新编译,确保 --with-luajit
no file './resty/http.lua' lua_package_path 未正确设置 检查 lua_package_path 配置
error loading module 'cjson' 找不到 cjson.so 检查 lua_package_cpath 配置
nginx: [emerg] bind() to 0.0.0.0:80 failed 端口被占用 sudo lsof -i :80 或换端口
opm: command not found 未在 PATH 中 export PATH=/usr/local/openresty/bin:$PATH

2.9 开发工具推荐

工具 用途 安装方式
VSCode + Lua 插件 IDE 编辑器 code --install-extension sumneko.lua
EmmyLua Lua 类型注解 VSCode 插件
chunkspy Lua 字节码查看 luarocks install chunkspy
resty-cli 命令行运行 Lua 随 OpenResty 安装
# 使用 resty 命令行测试 Lua 代码
resty -e 'ngx.say("Hello from resty-cli!")'

# 测试 Lua 库
resty -e 'local cjson = require "cjson"; print(cjson.encode({hello="world"}))'

上一章← 第 01 章 - OpenResty 概述 下一章第 03 章 - Nginx 与 Lua 执行阶段 →