cntchen.github.io icon indicating copy to clipboard operation
cntchen.github.io copied to clipboard

OpenResty 替换 Nginx

Open CntChen opened this issue 6 years ago • 0 comments

背景

OpenRestyNginx 的一个 bundle, 添加了许多拓展模块来增强 Nginx 的功能, 其亮点是支持 Lua 脚本, 大大提升了 Nginx 的请求处理能力并降低了配置难度.

刚好有个需求需要 Lua 脚本才能支持, 所以在 Mac 下使用 OpenResty 替换 Nginx.

Bundle vs Fork

业界有蛮多对 Nginx 的拓展, 主要的拓展方式有 bundle 和 fork.

  • Bundle

Bundle 是基于 Nginx core, 默认提供一些 Nginx 的组件来增强 Nginx 的功能. 如 OpenResty. Bundle 有突出的好处是可以方便地升级 Nginx core, 保持和官方 Nginx 的同步.

  • Fork

Fork 是基于某个版本的 Nginx 做二次开发, 实现各种 Nginx 不支持的功能. 如淘宝的 Tengine. Fork 的好处是提供了 Nginx 及 Nginx 插件无法实现的功能, 但是无法较好保持与官方 Nginx 的同步.

安装和启动 OpenResty

参考官方安装教程, 使用 brew 进行安装:

$ brew install openresty/brew/openresty

如果 Nginx 在运行则先停止 Nginx:

$ ps aux | grep nginx
nobody           12129   0.0  0.0  2503864      8   ??  S     5:58PM   0:00.01 nginx: worker process  
root                51   0.0  0.0  2502840      8   ??  Ss   Thu06PM   0:00.07 nginx: master process /usr/local/opt/nginx/bin/nginx -g daemon off;

$ sudo kill -9 51

启动 OpenResty:

$ sudo openresty

替换 nginx 命令

安装完毕后查看安装路径:

$ which openresty
/usr/local/bin/openresty
$ ls -al /usr/local/bin/openresty
lrwxr-xr-x  1 cntchen  admin  42 Jan  3 09:27 /usr/local/bin/openresty -> ../Cellar/openresty/1.13.6.1/bin/openresty

查看 nginx 命令路径:

$ which nginx
/usr/local/bin/nginx
$ ls -al /usr/local/bin/nginx
lrwxr-xr-x  1 cntchen  admin  32 Oct 25 17:25 /usr/local/bin/nginx -> ../Cellar/nginx/1.12.2/bin/nginx

nginx 命令给 OpenResty 使用:

# 保留 nginx 服务命令
$ mv nginx nginx-origin
$ rm nginx
$ ln -s ../Cellar/openresty/1.13.6.1/bin/openresty nginx

注意: 如果使用 brew upgrate 对 OpenResty 或 Nginx 进行升级, 会生成指向新版本的默认软链, 所以升级后需要手动处理一下.

对 OpenResty 进行配置

OpenResty 配置路径 /usr/local/etc/openresty.

Nginx 配置路径 /usr/local/etc/nginx.

将现有的 nginx 配置复制到 openresty 目录. 然后 reload OpenResty:

$ nginx -s reload

访问页面查看是否生效.

References

  • OpenResty

https://openresty.org/en/

  • Nginx

http://nginx.org/en/

  • Tengine

http://tengine.taobao.org/index_cn.html

  • Supercharge your Nginx with Openresty and Lua

https://dchua.com/2017/01/01/supercharge-your-nginx-with-openresty-and-lua/

EOF

CntChen avatar Jan 03 '18 02:01 CntChen