目录
1.安装OpenResty应用
首先我们需要在Linux中安装OpenResty,安装步骤参考官网:http://openresty.org/cn/installation.html。官方推荐我们使用官方预编译包来进行安装,因此真正的安装步骤是参考:http://openresty.org/cn/linux-packages.html,文章中详细列出了不同操作系统系统安装OpenResty的步骤。
1.使用 cat /proc/version 命令查看系统正在运行得内核版本
[root@VM_0_26_centos ~]# cat /proc/version
Linux version 3.10.0-693.el7.x86_64 ([email protected]) (gcc version 4.8.5 20150623 (Red Hat 4.8.5-16) (GCC) ) #1 SMP Tue Aug 22 21:09:27 UTC 2017
我的Linux系统版本为CentOS,所以参考安装http://openresty.org/cn/linux-packages.html中CentOS系统中安装预编译包步骤。
安装完成后,我们可以看一下安装好的OpenResty版本,我这里是1.15.8.2版本
2.注意事项
我们在执行 sudo yum-config-manager --add-repo https://openresty.org/package/centos/openresty.repo 这条命令时候可能会报出异常:
File "/bin/yum-config-manager", line 135
except yum.Errors.RepoError, e:
SyntaxError: invalid syntax
这是因为我的Linux中Python升级到了Python 3以上版本,需要修改/bin/yum-config-manager文件头为python2,修改后如下:
如果安装一切顺利,我们就开始部署OpenResty应用了。
2.新建项目
为了工作目录和OpenResty的安装目录不相互干扰,我们另外创建一个OpenResty的工作目录来练习,并新创建一个nginx.conf配置文件。我们选择在当前用户目录下创建/code/openresty目录,并在该目录下创建logs和conf子目录,执行命令如下:
mkdir ~/code/openresty/ ~/code/openresty/logs/ ~/code/openresty/conf/
然后在conf目录下执行 vim nginx.conf,并写入如下代码:
worker_processes 1;
error_log logs/error.log info;
events {
worker_connections 1024;
}
http {
default_type application/octet-stream;
access_log logs/access.log;
server {
listen 8001;
server_name localhost;
default_type text/html;
location /test {
content_by_lua_block {
ngx.say("Hello World")
}
}
}
}
在上述代码中我们输出一个Hello World
3.启动Nginx
万事具备只欠东风,我们启动Nginx即可。首先看一下nginx是否已经启动:
[root@VM_0_26_centos ~]# ps -ef | grep nginx
root 3823 1 0 17:35 ? 00:00:00 nginx: master process ./nginx -p /root/code/openresty/
nobody 3824 3823 0 17:35 ? 00:00:00 nginx: worker process
root 19450 19389 0 19:31 pts/1 00:00:00 grep --color=auto nginx
我的系统中,nginx已经启动,我先停掉nginx。
kill -QUIT 3823
然后,切换当前目录到OpenResty的安装目录:
cd /usr/local/openresty/
再切换到nginx目录
cd nginx/sbin/
执行nginx启动命令,并指定工作目录为:~/code/openresty/
[root@VM_0_26_centos sbin]# ./nginx -p ~/code/openresty/
[root@VM_0_26_centos sbin]# ps -ef | grep nginx
root 21783 1 0 19:49 ? 00:00:00 nginx: master process ./nginx -p /root/code/openresty/
nobody 21784 21783 0 19:49 ? 00:00:00 nginx: worker process
root 21800 19389 0 19:49 pts/1 00:00:00 grep --color=auto nginx
使用curl命令测试一下:curl http://localhost:8001/test -i
HTTP/1.1 200 OK
Server: openresty/1.15.8.2
Date: Tue, 07 Jan 2020 11:50:19 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: keep-alive
Hello World
在确定Nginx的时候,有可能出现 [emerg] unknown directive "content_by_lua_block" 异常,这是因为content_by_lua_block阶段没有被正常识别到,有两个原因可能引起该现象:
- 安装的openresty的版本过低,如果使用官方的预编译包来安装的话,不会是这个原因造成的
- 启动的 Nginx不是OpenResty自带的Nginx,需要切换到/usr/local/openresty/目录下启动Nginx
Congratulation!