09 . Nginx配置LNMP和LNMT架构

Posted 周常见(you-men)

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了09 . Nginx配置LNMP和LNMT架构相关的知识,希望对你有一定的参考价值。

安装LNMP架构

环境清单

list

CentOS7.
          nginx-1.18.0-1.el7.ngx.x86_64
  	  php-fpm-5.4.16-48.el7.x86_64
	  mysql-5.7.23-1.el7.x86_64.rpm-bundle.tar
主机 操作系统 IP地址 硬件/网络
Mysql105 CentOS7.3 192.168.0.105 2C4G / nat
Mysql106 CentOS7.3 192.168.0.106 2C4G / nat
Mysql107 CentOS7.3 192.168.0.107 2C4G / nat
ProxySQL109 CentOS7.3 192.168.0.109 2C4G / nat
安装Nginx
# 使用Nginx官方提供的rpm包
cat /etc/yum.repos.d/nginx.repo 
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/7/$basearch/
gpgcheck=0
enabled=1

yum -y install nginx
systemctl start nginx && systemctl enable nginx
安装PHP环境
yum -y install php php-fpm php-mysql php-gd gd
# 启动php
systemctl start php-fpm && systemctl enable php-fpm
安装Mysql
rpm -ivh http://repo.mysql.com/yum/mysql-5.7-community/el/7/x86_64/mysql57-community-release-el7-10.noarch.rpm

yum install mysql-community-server -y
systemctl start mysqld && systemctl enable mysqld

# 如果mysql登陆需要密码,请查看该文件
grep \'temporary password\' /var/log/mysqld.log
# 登陆mysql重新配置密码
mysql -uroot -p\'password\'
ALTER USER \'root\'@\'localhost\' IDENTIFIED BY \'ZHOUjian.21\';
配置LNMP架构

配置Nginx实现童泰请求转发至php

cat /etc/nginx/conf.d/default.conf 
server {
    listen       80;
    server_name  121.36.43.223; 
	location / {
		root html;
		index index.php index.html index.htm;
	}
	location ~ \\.php$ {
		root /usr/share/nginx/html;
    	fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
		fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include       fastcgi_params;
        }
}
nginx -s reload

添加php测试页面

# 测试phpinfo
cat /soft/code/info.php
<?php
        phpinfo();
?>
# 使用mysqli模块测试连接mysql
cat /usr/share/nginx/html/mysql.php 
<?php
$link=mysql_connect(\'localhost\',\'root\',\'ZHOUjian.20\');
if ($link)
	echo "Successfuly";
else
	echo "Failed";
mysql_close();
?>
检测LNMP架构
curl 121.36.43.223/info.php -I
HTTP/1.1 200 OK
Server: nginx/1.18.0
Date: Sun, 07 Jun 2020 09:57:24 GMT
Content-Type: text/html
Connection: keep-alive
X-Powered-By: PHP/5.4.16


curl 121.36.43.223/mysql.php
Successfuly
Nginx与PHP原理

# nginx fastcgi访问php
# 1.用户发送http请求报文给nginx服务器
# 2.nginx会根据文件url和后缀来判断请求
# 3.如果请求的是静态内容,nginx会将结果直接返回给用户
# 4.如果请求的是动态内容,nginx会将请求交给fastcgi客户端,通过fastcgi_pass将这个请求发送给php-fpm
# 5.php-fpm收到请求后会通过本地监听的socket交给wrapper
# 6.wrapper收到请求会生成新的线程调用php动态程序解析服务器
# 7.如果用户请求的是博文、或者内容、PHP会请求MySQL查询结果
# 8.如果用户请求的是图片、附件、PHP会请求nfs存储查询结果
# 9.php会将查询到的结果交给Nginx
# 10.nginx会生成一个响应报文返还给用户
PHP配置文件优化
//打开php的安全模式,控制php执行危险函数, 默认是Off,改为On
sql.safe_mode = Off
//关闭php头部信息, 隐藏版本号, 默认是On,该为Off
expose_php = On
//错误信息输出控制
display_error = Off
error_reporting = E_WARNING & E_ERROR
//记录错误日志至后台, 方便追溯
log_errors = On
error_log = /var/log/php_error.log
//每个脚本时间最大内存
memory_limit = 128M
//上传文件最大许可,默认2M, 建议调整为16,32M
upload_max_filesize = 2M
//禁止远程执行phpshell,默认On, 建议Off
allow_url_fopen = On
//时区调整,默认PRC, 建议调整为Asia/Shanghai
date.timezone = PRC
//整体优化后配置文件
sql.safe_mode = Off
expose_php = Off
display_error = Off
error_reporting = E_WARNING & E_ERROR
log_errors = On
error_log = /var/log/php_error.log
upload_max_filesize = 50M
allow_url_fopen = Off
date.timezone = Asia/Shanghai
PHP-FPM优化
PHP-FPM配置文件 4核16G、8核16G
[root@nginx ~]# cat /etc/php-fpm.d/www.conf
[global]
pid = /var/run/php-fpm.pid
#php-fpm程序错误日志
error_log = /var/log/php/php-fpm.log
log_level = warning
rlimit_files = 655350
events.mechanism = epoll
[www]
user = nginx
group = nginx
listen = 127.0.0.1:9000
listen.owner = www
listen.group = www
listen.mode = 0660

listen.allowed_clients = 127.0.0.1
pm = dynamic
pm.max_children = 512
pm.start_servers = 10
pm.min_spare_servers = 10
pm.max_spare_servers = 30
pm.process_idle_timeout = 15s;

pm.max_requests = 2048
#php-www模块错误日志
php_flag[display_errors] = off
php_admin_value[error_log] = /var/log/php/php-www.log
php_admin_flag[log_errors] = on
#php慢查询日志
request_slowlog_timeout = 5s
slowlog = /var/log/php/php-slow.log
PHP5-FPM配置详解释
[global]
#pid设置, 记录程序启动后pid
pid = /var/run/php-fpm.pid
#php-fpm程序启动错误日志路径
error_log = /soft/log/php/php-fpm_error.log
# 错误级别. 可用级别为: alert(必须立即处理),error(错误情况), warning(警告情况), notice(一般重要信息), debug(调试信息). 默认: notice.
log_level = warning
#设置文件打开描述符的rlimit限制.
rlimit_files = 65535
events.mechanism = epoll
#启动进程的用户和组
[www]
user = www
group = www
# fpm监听端口
listen = 127.0.0.1:9000
# unix socket设置选项,如果使用tcp方式访问,这里注释即可。
listen.owner = www
listen.group = www
# 允许访问FastCGI进程的IP,any不限制
listen.allowed_clients = 127.0.0.1
# pm设置动态调度
pm = dynamic
# 同一时刻最大的php-fpm子进程数量
pm.max_children = 200
# 动态方式下的起始php-fpm进程数量
pm.start_servers = 20
# 动态方式下服务器空闲时最小php-fpm进程数量
pm.min_spare_servers = 10
# 动态方式下服务器空闲时最大php-fpm进程数量
pm.max_spare_servers = 30
# 最大请求
pm.max_requests = 1024
pm.process_idle_timeout = 15s;
# FPM状态页面,用于监控php-fpm状态使用
pm.status_path = /status
# 错误日志
php_flag[display_errors] = off
php_admin_value[error_log] = /soft/log/php/php-www_error.log
php_admin_flag[log_errors] = on
# 配置php慢查询, 以及慢查询记录日志位置
request_slowlog_timeout = 5s
slowlog = /soft/log/php/php-slow.log

配置LNMT架构

Tomcat虚拟主机
     一个应用程序在某一个端口启动运行产生了一系列的进程就是一个实例,让tomcat启动两个不同的相互独立的进程,产生两个不同的套接字,分别运行在不同的端口,让不同的端口响应不同的请求,就是多实例.

作用

# 1.多个实例运行相同的应用,实现负载均衡,支持高并发处理,解决session问题.
# 2.多个实例运行不同的应用(类似虚拟主机)
多实例Example

配置三个Tomcat实例,分别运行/webapps/ROOT下的同一网站,达到负载均衡的作用

实例目录 工作端口 实例端口
tomcat_instance1: /usr/local/tomcat/instance1/{conf,logs,temp,work} 8081 8091
tomcat_instance2: /usr/local/tomcat/instance1/{conf,logs,temp,work} 8082 8092
tomcat_instance3: /usr/local/tomcat/instance1/{conf,logs,temp,work} 8083 8093
先部署单节点Tomcat

1.安装JDK环境

# CentOS7安装Java,有tar包和rpm包两种
        1>. rpm -ivh jdk-8u121-linux-x64.rpm
        2>. tar xvf jdk-8u151-linux-x64.tar.gz -C /usr/local/
cd /usr/local/
mv jdk1.8.0_151/ jdk
tail -3 /etc/profile
JAVA_HOME=/usr/local/jdk
export PATH=$JAVA_HOME/bin:$PATH
export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
source /etc/profile

2.安装Tomcat

wget https://mirrors.tuna.tsinghua.edu.cn/apache/tomcat/tomcat-8/v8.5.55/bin/apache-tomcat-8.5.55.tar.gz
tar xvf apache-tomcat-8.5.47.tar.gz -C /usr/local/
ln -s /usr/local/apache-tomcat-8.5.47/ /usr/local/tomcat
tail -1 /etc/profile
export CATALINA_HOME=/usr/local/tomcat

source /etc/profile
env |grep -i home
CATALINA_HOME=/usr/local/tomcat
HOME=/root

# 查看熵池的大小: 
cat /proc/sys/kernel/random/entropy_avail 180
增加熵池大小,解决Tomcat在CentOS 7巨慢的问题

# 安装rng服务,增大熵池
yum -y install rng-tools
systemctl start rngd && systemctl enable rngd
# 启动服务访问Tomcat页面快一百倍..

3.启动Tomcat

/usr/local/tomcat/bin/catalina.sh start
# ss -antp |grep java
# LISTEN     0      100          *:8009                     *:*                   users:(("java",pid=857,fd=58))
# LISTEN     0      100          *:8080                     *:*                   users:(("java",pid=857,fd=53))
# LISTEN     0      1      127.0.0.1:8005                     *:*                   users:(("java",pid=857,fd=73))
/usr/local/tomcat/bin/shutdown.sh

配置多实例目录

mkdir /webapps/ROOT -p
echo "welcome to tomcat mulit instance" > /webapps/ROOT/index.jsp
echo "hello everyone" > /webapps/ROOT/a.jsp
mkdir -p /usr/local/tomcat/instance{1,2,3}/{conf,logs,temp,work}
配置实例server.xml
\\cp /usr/local/tomcat/conf/* /usr/local/tomcat/instance1/conf/
\\cp /usr/local/tomcat/conf/* /usr/local/tomcat/instance2/conf/
\\cp /usr/local/tomcat/conf/* /usr/local/tomcat/instance3/conf/

# Context配置
# Context作用
# 路径映射
# 应用独立配置,例如单独配置应用日志,单独配置应用访问控制

vim /usr/local/tomcat/instance1/conf/server.xml
<Server port="8091" shutdown="SHUTDOWN">       # 管理实例端口
<Connector port="8081" protocol="HTTP/1.1"     # 提供web服务端口
connectionTimeout="20000"
redirectPort="8443" />
<Host name="localhost" appBase="/webapps"      
# 如果两个实例对应两个不同的页面,那么直接修改appBase后端的路径就可以了
unpackWARs="true" autoDeploy="true">

vim /usr/local/tomcat/instance2/conf/server.xml
<Server port="8092" shutdown="SHUTDOWN">
<Connector port="8082" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
<Host name="localhost" appBase="/webapps"
unpackWARs="true" autoDeploy="true">

vim /usr/local/tomcat/instance3/conf/server.xml
<Server port="8093" shutdown="SHUTDOWN">
<Connector port="8083" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
<Host name="localhost" appBase="/webapps"
unpackWARs="true" autoDeploy="true">
创建一个脚本方便启动
chmod +x /usr/local/tomcat/instance1/ins1.sh    
#每个tomcat下的instance都要创建一个ins1.sh,并且修改里面的instance
#!/bin/bash
#instace1 script
export JAVA_OPTS=\'-Xms64m -Xmx128m\'

#tomcat实例启动时最小分配的内存为64M,最大为128M
export CATALINA_HOME=/usr/local/tomcat
#tomcat的安装目录
export CATALINA_BASE=/usr/local/tomcat/instance1
#实例1的目录
case $1 in
start)
  $CATALINA_HOME/bin/startup.sh
  ;;
stop)
  $CATALINA_HOME/bin/shutdown.sh
  ;;
restart)
  $CATALINA_HOME/bin/shutdown.sh
  sleep 3
  $CATALINA_HOME/bin/startup.sh
  ;;
esac

chmod +x /usr/local/tomcat/instance1/ins1.sh
cp instance1/ins1.sh instance2/
cp instance1/ins1.sh instance3/
vim instance3/ins1.sh
vim instance2/ins1.sh        # 修改tomcat安装目录instanace分别对应什么目录即可

/usr/local/tomcat/instance1/ins1.sh start
/usr/local/tomcat/instance2/ins1.sh start
/usr/local/tomcat/instance3/ins1.sh start

elinks --dump 39.108.140.0:8081
#   welcome to tomcat mulit instance
elinks --dump 39.108.140.0:8082
#   welcome to tomcat mulit instance
elinks --dump 39.108.140.0:8083
#   welcome to tomcat mulit instance
Nginx+Tomcat负载均衡

用户在访问时,需要手动输入端口号,所以需要一个代理服务器,使用nginx做代理,用户访问nginx,然后由nginx访问后端的tomcat。代理方案有两种.

客户端所有请求全部代理到后端Tomcat服务器

修改配置文件,重启服务
# 为了测试看效果使用不同的页面
mkdir /webapp{1..3}
mkdir /webapps1/ROOT
mkdir /webapps2/ROOT
mkdir /webapps3/ROOT
echo webapp1 > /webapps1/ROOT/index.jsp
echo webapp2 > /webapps2/ROOT/index.jsp
echo webapp3 > /webapps3/ROOT/index.jsp
vim /usr/local/tomcat/instance1/conf/server.xml # 分别修改三个配置文件的appBase
vim /usr/local/tomcat/instance2/conf/server.xml
vim /usr/local/tomcat/instance3/conf/server.xml

# 除了修改配置文件appBase,为保证后端Tomcat服务器的日志可以记录客户端真实IP
vim /usr/local/tomcat/instance1/conf/server.xml
prefix="localhost_access_log" suffix=".txt"
               pattern="**%{x-real-ip}i** %l %u %t &quot;%r&quot; %s %b" />

/usr/local/tomcat/instance3/ins1.sh start
/usr/local/tomcat/instance2/ins1.sh start
/usr/local/tomcat/instance1/ins1.sh start
配置Nginx
vim /etc/nginx/nginx.conf
http {
upstream tomcatsrv {
    server 39.108.140.0:8081 weight=1 max_fails=2 fail_timeout=2;
    server 39.108.140.0:8082 weight=1 max_fails=2 fail_timeout=2;
    server 39.108.140.0:8083 weight=1 max_fails=2 fail_timeout=2;
}

vim /etc/nginx/conf.d/default.conf
server {
    listen       80;
    server_name localhost;
    location / {
        proxy_pass http://tomcatsrv;
        proxy_set_header x-real-ip $remote_addr;
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
nginx -s reload
elinks --dump 39.108.140.0
   webapp1
elinks --dump 39.108.140.0
   webapp2
elinks --dump 39.108.140.0
   webapp3
# 我们去看下tomcat日志是否记录了真实日志
tail -2 /usr/local/tomcat/instance1/logs/localhost_access_log.2019-11-05.txt
39.108.140.0 - - [05/Nov/2019:12:28:17 +0800] "GET / HTTP/1.0" 200 8
47.92.24.137 - - [05/Nov/2019:12:35:13 +0800] "GET / HTTP/1.0" 200 8

客户端访问静态页面由Nginx解析,客户端如访问jsp页面访问请求代理到后端Tomcat服务器
只需要准备一台能解析静态页面的nginx,或者httpd,修改下配置文件即可

vim /etc/nginx/nginx.conf
http {
upstream nginxsrv {
    server 49.233.69.195:80 weight=1 max_fails=2 fail_timeout=2;
    }

upstream tomcatsrv {
    server 39.108.140.0:8081 weight=1 max_fails=2 fail_timeout=2;
    server 39.108.140.0:8082 weight=1 max_fails=2 fail_timeout=2;
    server 39.108.140.0:8083 weight=1 max_fails=2 fail_timeout=2;
    }

vim /etc/nginx/conf.d/default.conf
    location ~* \\.html$ {
        root /usr/share/nginx/html;
        index index.html index.htm;
         proxy_pass http://nginxsrv;
         proxy_set_header x-real-ip $remote_addr;
    }

    location ~* \\.jsp$ {
        proxy_pass http://tomcatsrv;
        proxy_set_header x-real-ip $remote_addr;
    }

nginx -s reload
elinks --dump 39.108.140.0/index.html
   welcome to nginx
elinks --dump 39.108.140.0/index.jsp
   webapp1
elinks --dump 39.108.140.0/index.jsp
   webapp2

如果tomcat上面搭建的是一个实际的网站,点击登录去登录,却发现登录不成功,可能是session会话不一致的问题
session(会话) 暂时没有使用共享方式,目前采用的会话保持,软件方面可以通过会话同步到数据库是实现session会话共享。

或者前方代理比如Nginx使用ip_hash之类的算法,一个用户固定访问后端的一个web服务器

即将同一个client的访问始终调度到同一后端实例.后面文章有写如何使用redis共享会话,请看下面这篇链接

https://www.cnblogs.com/you-men/p/13045736.html

以上是关于09 . Nginx配置LNMP和LNMT架构的主要内容,如果未能解决你的问题,请参考以下文章

LNMT架构部署:Linux+Nginx+Mysql+Tomcat(负载均衡,动静分离)

Linux中详细搭建lnmt架构

部署LNMP架构

lnmp架构之nginx

lnmp架构之nginx

LNMP架构应用实战——Nginx配置虚拟主机