Debian/Ubuntu 下 Nginx+Lua 环境搭建

前言

  • 关于lua的特性不再赘述;
  • 以下步骤均使用了apt-get进行操作,免去了诸如ng-lua组件手动加载等繁琐的步骤,妄图使用其他方式安装的请移步官方文档:https://github.com/openresty/lua-nginx-module#installation
  • lua在web上基于lua-nginx-module运作,目前还没有Apache的支持组件,所以妄图使用Apache的可以撤了;

本人环境供参考:

Distributor ID: Debian
Description:    Debian GNU/Linux 8.8 (jessie)
Release:    8.8
Codename:   jessie

注:不确定wheezy版本的Linux下luajit是否可用。

搭建步骤

1、首先确定自己的APT源是否可用,是否足够新.

本人最开始使用了一个较为老旧的dotdeb版本,导致apt-cache查询不到lua-nginx-module,甚至一度尝试手动加载该模块,由此浪费了许多时间;
本人使用的apt source list供参考:

sudo vi /etc/apt/sources.list

>
deb http://mirrors.aliyun.com/dotdeb jessie all
deb http://mirrors.aliyun.com/debian jessie main contrib non-free
deb http://mirrors.aliyun.com/debian jessie-updates main contrib non-free
deb http://mirrors.aliyun.com/debian-security jessie/updates main contrib non-free

需要注意的是:添加源的时候需要注意完整性,本人最开始图省事,仅用了一个all,发现apt并不能找到luajit模块,又浪费了很多时间。

2、没有nginx的先安装nginx;

不再赘述

sudo apt-get install nginx-full

3、安装lua及相关组件

不再赘述

apt-get install lua5.2 lua5.2-doc liblua5.2-dev

4、安装luajit

sudo apt-get install luajit

关于JIT :

通常,程序有两种运行方式:静态编译与动态直译。
静态编译的程序在执行前全部被翻译为机器码,而动态直译执行的则是一句一句边运行边翻译。
即时编译(Just-In-Time Compiler)则混合了这二者,一句一句编译源代码,但是会将翻译过的代码缓存起来以降低性能损耗。

此外,使用luajit可以大大提高lua的运行效率,由此也被官方钦定。

It is highly recommended to use OpenResty releases which integrate Nginx, ngx_lua, LuaJIT 2.1, as well as other powerful companion Nginx modules and Lua libraries.

5、安装nginx的lua模块 lua-nginx-module

sudo apt-get install libnginx-mod-http-lua

需要注意的是:如果前面apt源不够新或不够全,很可能会在安装此模块的时候出现找不到luajit依赖项的情况,此时请寻找新的可靠的源并确保完整性,不要在这里浪费时间。

6、配置nginx

nginx的配置中,核心在于content_by_lua_file。

关于 content_by_lua_file 的官方文档: https://github.com/openresty/lua-nginx-module#content_by_lua_file

本人的配置代码供参考:

server {
            listen 80;
            server_name ebid.xxxx.com;
            root /home/separes/xxx;

            location / {
                    lua_code_cache off;  // 缓存
                    content_by_lua_file /home/separes/xxx/index.o;
            }
}

需要注意的是:这里的nginx缓存是默认开启的,推荐调试及开发环境中手动关闭 lua_code_cache。

7、其它

这里推荐几个组件

// cjson
sudo apt-get install lua-cjson

// lyaml
sudo luarocks install lyaml

// dbi
sudo luarocks install luadbi-mysql MYSQL_INCDIR=/usr/include/mysql
//实测后面必须指定MYSQL路径,指向系统中的mysql根目录,匹配mysql.c文件

需要注意的是,使用 luarocks/apt-get 安装或升级 lua-DBI 的时候,需要注意新版本的DBI并不完全向下兼容,其中dbi参数由全局变量改为了局部变量,如果在以前的代码中使用过,需要重新进行声明,否则该参数会报错。

文档:

Lua官方文档: https://www.lua.org/manual/5.3

lua-nginx-module官方文档: https://github.com/openresty/lua-nginx-module

环境搭建至此为止。

标签:LUADebianUbuntuNginx 发布于:2019-11-08 11:14:49