openresty实现nginx+lua

  之前直接用nginx+lua,实在麻烦,用openresty简单多了。更简单的是用docker实现openresty,参考链接:Docker 安装OpenResty,步骤如下:

1、拉取镜像:docker pull openresty/openresty

2、启动:docker run --name openresty -p 80:80 -d openresty/openresty

3、创建宿主机目录(用于映射进docker):

mkdir -p /app/docker/openresty/conf
mkdir -p /app/docker/openresty/html
mkdir -p /app/docker/openresty/lua
mkdir -p /app/docker/openresty/logs

4、拷贝容器中文件到宿主机目录

//拷贝nginx配置文件
docker cp openresty:/usr/local/openresty/nginx/conf/nginx.conf /app/docker/openresty/conf
//拷贝lua库
docker cp openresty:/usr/local/openresty/lualib /app/docker/openresty/lua

5、删除容器,新建容器:

//删除容器
docker rm -f openresty

//启动
docker run --name openresty \
-v /app/docker/openresty/conf/nginx.conf:/usr/local/openresty/nginx/conf/nginx.conf \
-v /app/docker/openresty/lua/:/usr/local/openresty/lualib \
-v /app/docker/openresty/html/:/usr/local/openresty/nginx/html \
-v /app/docker/openresty/logs/:/usr/local/openresty/nginx/logs \
-p 8080:80 -d openresty/openresty

6、配置容器:

# /app/docker/openresty/lua/test.lua
ngx.say('{"id" : "10086", "name":"test"}')
# /app/docker/openresty/conf/nginx.conf
http {
    server_tokens off;
    include       mime.types;
    default_type  application/octet-stream;
    underscores_in_headers on;#表示如果header name中包含下划线,则不忽略

    sendfile        on;
    #keepalive_timeout  0;
    keepalive_timeout  65;
    gzip  on;
    #include /etc/nginx/conf.d/*.conf;
    #lua 模块
    lua_package_path "/usr/local/openresty/lualib/?.lua;;";
    #c模块     
    lua_package_cpath "/usr/local/openresty/lualib/?.so;;";  
    server {
        listen       80;
        server_name  127.0.0.1;
        location /test {
            # 默认的响应类型
            default_type application/json;ng
            content_by_lua_file lua/test.lua;
        }
        
        location / {
            root   html;
            index  index.html index.htm;
        }
   }
}

7、进入容器,删除default.conf。这个文件中有默认的80端口配置,会影响nginx.conf文件中的配置。参考链接中没有这个动作

docker exec -it openresty/openresty /bin/bash
mv /etc/nginx/conf.d/default.conf /etc/nginx/conf.d/default.conf.back

8、测试:

curl http://localhost:8080/test
{"id" : "10086", "name":"test"}

 

posted @ 2024-05-15 22:50  badwood  阅读(43)  评论(0编辑  收藏  举报
Badwood's Blog