CentOS搭建LNMP

CentOS搭建LNMP

前言:
我这里会讲解lamp架构的安装到配置,以及安装过程中的一些报错点

提示:这里的安装包括源码安装和yum安装

什么是lnmp?

nginx服务也通常和mysql、php一起使用,而这些通常都在linux系统下去运行,大家听说过lamp那lnmp概念也一样,就是把httpd服务替换成了nginx而已 lamp = linux + nginx + mysql + php

一、源码编译安装部署lnmp

★安装之前的准备工作★

我这里使用的环境如下:
系统:CentOS7.9
ip地址:192.168.31.101
安装包:
nginx-1.21.6.tar.gz
mysql-boost-5.7.36.tar.gz
php-7.4.28.tar.gz

注意:需要多注意这些安装包的版本兼容性

安装包下载地址

nginx下载地址:http://nginx.org/download/
mysql下载地址:https://downloads.mysql.com/archives/community/
php下载地址:https://www.php.net/downloads.php

关闭防火墙和selinux

systemctl stop firewalld
setenforce 0

安装epel源,这样方便安装一些依赖包,要不然yum会没有一些包,再安装所需要的编译工具

yum install -y epel-release
yum clean all && yum makecache
yum -y install gcc gcc-g++ cmake make

现在就可以正式开始安装了。。。。。。
这里的安装顺序建议是php一般放到最后来,它是nginx和mysql的中间人,协调工作。

1.安装nginx

1.安装编译nginx时所需要的依赖包

yum -y install openssl openssl-devel pcre-devel curl-devel freetype-devel

2.创建nginx程序运行使用的用户

groupadd nginx && useradd -M -s /sbin/nologin nginx -g nginx

3.解压安装包编译安装nginx

tar zxf nginx-1.21.6.tar.gz && cd nginx-1.21.6
./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_stub_status_module
make && make install

跟apache一样这里可以用./configure --help查询编译可以使用的一些参数
–prefix=/usr/local/nginx :指定安装路径

4.编辑nginx配置文件

vim /usr/local/nginx/conf/nginx.conf
-----------------------------------------
user  nginx;
worker_processes  1;
error_log  logs/nginx_error.log;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  300;
    server {
        listen       80;
        server_name  localhost;
        access_log  logs/nginx80.access.log;
        location / {
            root   /var/www/html;
            index  index.html index.php;
        }
        location ~ \.php$ {
            root           /var/www/html;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

其中需要修改的就是
index index.php;
还有就是加入支持php转发到9000端口处理
location ~ .php$ {
root /var/www/html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME d o c u m e n t r o o t document_root documentrootfastcgi_script_name;
include fastcgi_params;
}

查看nginx配置文件是否有问题

/usr/local/nginx/sbin/nginx -t

5.启动nginx服务

/usr/local/nginx/sbin/nginx

6.添加nginx服务到systemctl并优化服务命令路径(补充,也可以不要这一步骤,看个人)
nginx管理脚本:

vim /etc/init.d/nginx
-----------------------------------------
#!/bin/bash
# chkconfig: 2345 30 21
# description: http service.
# Source Function Library
. /etc/init.d/functions
# Nginx Settings
NGINX_SBIN="/usr/local/nginx/sbin/nginx"
NGINX_CONF="/usr/local/nginx/conf/nginx.conf"
NGINX_PID="/usr/local/nginx/logs/nginx.pid"
RETVAL=0
prog="Nginx"
start() {
echo -n $"Starting $prog: "
mkdir -p /dev/shm/nginx_temp
daemon $NGINX_SBIN -c $NGINX_CONF
RETVAL=$?
echo
return $RETVAL
}
stop() {
echo -n $"Stopping $prog: "
killproc -p $NGINX_PID $NGINX_SBIN -TERM
rm -rf /dev/shm/nginx_temp
RETVAL=$?
echo
return $RETVAL
}
reload(){
echo -n $"Reloading $prog: "
killproc -p $NGINX_PID $NGINX_SBIN -HUP
RETVAL=$?
echo
return $RETVAL
}
restart(){
stop
start
}
configtest(){
$NGINX_SBIN -c $NGINX_CONF -t
return 0
}
case "$1" in
start)
start
;;
stop)
stop
;;
reload)
reload
;;
restart)
restart
;;
configtest)
configtest
;;
*)
echo $"Usage: $0 {start|stop|reload|
restart|configtest}"
RETVAL=1
esac
exit $RETVAL

添加权限加入chkconfig

chmod +x /etc/init.d/nginx
chkconfig --add nginx
pkill nginx
systemctl restart nginx

2.安装mysql

1.yum安装mysql所需要的依赖包

yum -y install openssl openssl-devel prce pcre-devel bison bison-devel ncurses-devel

2.创建mysql用户给mysql程序使用

groupadd mysql && useradd -M -s /sbin/nologin mysql -g mysql

3.解压安装包,使用cmake工具编译安装mysql

#解压安装包
tar zxf mysql-boost-5.7.36.tar.gz && cd mysql-5.7.36
#cmake编译安装mysql
cmake -DCMAKE_INSTALL_PREFIX=/usr/local/mysql -DMYSQL_DATADIR=/usr/local/mysql/data -DSYSCONFDIR=/etc -DWITH_BOOST=boost -DWITH_MYISAM_STORAGE_ENGINE=1 -DWITH_INNOBASE_STORAGE_ENGINE=1 -DWITH_MEMORY_STORAGE_ENGINE=1 -DWITH_READLINE=1 -DMYSQL_UNIX_ADDR=/var/lib/mysql/mysql.sock -DMYSQL_TCP_PORT=3306 -DENABLED_LOCAL_INFILE=1 -DWITH_PARTITION_STORAGE_ENGINE=1 -DEXTRA_CHARSETS=all -DDEFAULT_CHARSET=utf8 -DDEFAULT_COLLATION=utf8_general_ci
make && make install

注意:在编译的时候注意一些参数跟下面第4点和第5点的参数和目录有联系,修改需谨慎,免得服务起不来找问题麻烦

编译的时间可能会等的有点久.。。。。。。就耐心等待吧!!!

4.使用mysql自带的mysqld命令初始化数据库,准备工作

/usr/local/mysql/bin/mysqld --user=mysql --basedir=/usr/local/mysql --datadir=/usr/local/mysql/data --pid-file=/usr/local/mysql/run/mysql.pid --initialize

这里初始化完成之后你会发现在你安装mysql的目录会自动生成data目录,这里还加载了mysql的pid文件的生成目录,记载mysql的pid进程号

5.创建准备mysql的一些工作目录

#创建日志目录并创建错误日志文件
mkdir -p /usr/local/mysql/run /usr/local/mysql/logs
touch /usr/local/mysql/logs/mysql_error.log
#把mysql的安装目录属主改为mysql,授权mysql程序pid运行目录755
chown -R mysql.mysql /usr/local/mysql
chmod 755 /usr/local/mysql/run

6.编辑mysql的配置文件

vim /etc/my.cnf
-----------------------------------------
[client]  
socket = /usr/local/mysql/mysql.sock
[mysqld]
skip-grant-tables
port = 3306 
user = mysql
character-set-server=utf8
socket = /usr/local/mysql/mysql.sock
pid-file = /usr/local/mysql/run/mysql.pid
log-error = /usr/local/mysql/logs/mysql_error.log
basedir = /usr/local/mysql
datadir = /usr/local/mysql/data
[mysqld_safe]
pid-file = /usr/local/mysql/run/mysql.pid
log-error = /usr/local/mysql/logs/mysql_error.log

7.启动服务并初始化服务密码
启动脚本在/usr/local/mysql/support-files这个目录下

/usr/local/mysql/support-files/mysql.server start

查看服务启动状态(mysql默认是3306端口)
netstat -anptu |grep 3306
lamp.003
登录数据库设置root密码

mysql -uroot -p

因为配置文件设置了skip-grant-tables参数,所以不需要密码直接进入,开始设置密码

flush privileges;
#进入mysql库下,修改root用户密码为123456
use mysql;
set password for root@localhost=password('123456');
#默认是只能本地登录,授权root用户所有地址都能登录
grant all privileges on *.* to 'root'@'%' identified by '123456' with grant option;
flush privileges;

修改配置文件把skip-grant-tables这个参数注释掉(前面加上#号就行)或者删除,再重启服务
#skip-grant-tables
这里大家可以先去完成第8步直接使用systemctl命令重启

pkill mysqld
/usr/local/mysql/support-files/mysql.server start

mysql安装就完成了,可以使用了!!!

8.添加mysqld服务到systemctl并优化服务命令路径(补充,也可以不要这一步骤,看个人)

#mysqld服务加入systemctl方便管理,跟上面httpd服务原理一样
cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld
chmod +x /etc/init.d/mysqld
chkconfig --add mysqld
systemctl restart mysqld
systemctl status mysqld
#优化命令路径
ln -s /usr/local/mysql/bin/* /usr/bin

3.安装php

1.yum安装php所需要的依赖包

yum -y install php-bcmath php-mbstring sqlite-devel oniguruma-devel curl-devel freetype-devel libjpeg-devel libpng-devel libxslt-devel libxml2-devel zlib-devel

2.解压php安装包并编译

tar zxf php-7.4.28.tar.gz && cd php-7.4.28
 ./configure --prefix=/usr/local/php7.4 --enable-gd --with-jpeg --with-freetype --with-curl --with-zlib --with-zlib-dir --with-mysqli --with-config-file-path=/usr/local/php7.4 --enable-mysqlnd --enable-mbstring --enable-fpm --enable-bcmath --enable-sockets --enable-shared --with-gettext --with-openssl --with-pdo-mysql
 make && make install

注意:--with-apxs2=/usr/local/httpd/bin/apxs这个选项不用加,是apache的模块

这里也同样可以使用./configure --help查询编译可以使用的一些参数
3.创建php用户和用户组

groupadd php && useradd -M -s /sbin/nologin php -g php
```powershell
4.编辑php配置文件
```bash
vim /usr/local/php7.4/php.ini
------------------------------------------
[PHP]
date.timezone = "Asia/Shanghai"
engine = On
short_open_tag = Off
precision = 14
output_buffering = 4096
zlib.output_compression = Off
implicit_flush = Off
unserialize_callback_func =
serialize_precision = -1
disable_functions =
disable_classes =
zend.enable_gc = On
zend.exception_ignore_args = Off
expose_php = On
max_execution_time = 300
max_input_time = 300
memory_limit = 128M
post_max_size = 16M
error_reporting = E_ALL
display_errors = On
display_startup_errors = On
log_errors = On
log_errors_max_len = 1024
ignore_repeated_errors = Off
ignore_repeated_source = Off
report_memleaks = On
variables_order = "GPCS"
request_order = "GP"
register_argc_argv = Off
auto_globals_jit = On
auto_prepend_file =
auto_append_file =
default_mimetype = "text/html"
default_charset = "UTF-8"
doc_root =
user_dir =
enable_dl = Off
file_uploads = On
upload_max_filesize = 2M
max_file_uploads = 20
allow_url_fopen = On
allow_url_include = Off
default_socket_timeout = 60
extension=curl
extension=fileinfo
extension=gd2
extension=mysqli
extension=pdo_mysql
extension=pdo_odbc
[CLI Server]
cli_server.color = On
[Date]
[filter]
[iconv]
[imap]
[intl]
[sqlite3]
[Pcre]
[Pdo]
[Pdo_mysql]
pdo_mysql.default_socket=/usr/local/mysql/mysql.sock
[Phar]
[mail function]
SMTP = localhost
smtp_port = 25
mail.add_x_header = Off
[ODBC]
odbc.allow_persistent = On
odbc.check_persistent = On
odbc.max_persistent = -1
odbc.max_links = -1
odbc.defaultlrl = 4096
odbc.defaultbinmode = 1
[MySQLi]
mysqli.max_persistent = -1
mysqli.allow_persistent = On
mysqli.max_links = -1
mysqli.default_port = 3306
mysqli.default_socket =/usr/local/mysql/mysql.sock
mysqli.default_host =
mysqli.default_user =
mysqli.default_pw =
mysqli.reconnect = Off
[mysqlnd]
mysqlnd.collect_statistics = On
mysqlnd.collect_memory_statistics = On
[OCI8]
[PostgreSQL]
pgsql.allow_persistent = On
pgsql.auto_reset_persistent = Off
pgsql.max_persistent = -1
pgsql.max_links = -1
pgsql.ignore_notice = 0
pgsql.log_notice = 0
[bcmath]
bcmath.scale = 0
[browscap]
[Session]
session.save_handler = files
session.use_strict_mode = 0
session.use_cookies = 1
session.use_only_cookies = 1
session.name = PHPSESSID
session.auto_start = 0
session.cookie_lifetime = 0
session.cookie_path = /
session.cookie_domain =
session.cookie_httponly =
session.cookie_samesite =
session.serialize_handler = php
session.gc_probability = 1
session.gc_divisor = 1000
session.gc_maxlifetime = 1440
session.referer_check =
session.cache_limiter = nocache
session.cache_expire = 180
session.use_trans_sid = 0
session.sid_length = 26
session.trans_sid_tags = "a=href,area=href,frame=src,form="
session.sid_bits_per_character = 5
[Assertion]
zend.assertions = 1
[COM]
[mbstring]
[gd]
[exif]
[Tidy]
tidy.clean_output = Off
[soap]
soap.wsdl_cache_enabled=1
soap.wsdl_cache_dir="/tmp"
soap.wsdl_cache_ttl=86400
soap.wsdl_cache_limit = 5
[sysvshm]
[ldap]
ldap.max_links = -1
[dba]
[opcache]
[curl]
[openssl]
[ffi]

5.编辑php-fpm配置文件

vim /usr/local/php7.4/etc/php-fpm.conf
---------------------------------------------------
;;;;;;;;;;;;;;;;;;;;;
; FPM Configuration ;
;;;;;;;;;;;;;;;;;;;;;
[global]
pid = run/php-fpm.pid
error_log = log/php-fpm_error.log
include=/usr/local/php7.4/etc/php-fpm.d/*.conf

编辑www.conf子配置文件

vim /usr/local/php7.4/etc/php-fpm.d/www.conf
---------------------------------------------------
[www]
user = php
group = php
listen = 127.0.0.1:9000
pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3

6.启动php-fpm

/usr/local/php7.4/sbin/php-fpm

7.编写php-fpm管理脚本,优化php命令路径
php-fpm管理脚本:

vim /etc/init.d/php-fpm
-----------------------------------------
#! /bin/sh
### BEGIN INIT INFO
# Provides:     php-fpm
# Required-Start:  $remote_fs $network
# Required-Stop:   $remote_fs $network
# Default-Start:   2 3 4 5
# Default-Stop:   0 1 6
# Short-Description: starts php-fpm
# Description:    starts the PHP FastCGI Process Manager daemon
### END INIT INFO
prefix=/usr/local/php7.4
exec_prefix=${prefix}
php_fpm_BIN=${exec_prefix}/sbin/php-fpm
php_fpm_CONF=${prefix}/etc/php-fpm.conf
php_fpm_PID=${prefix}/var/run/php-fpm.pid
php_opts="--fpm-config $php_fpm_CONF --pid $php_fpm_PID"
wait_for_pid () {
  try=0
  while test $try -lt 35 ; do
    case "$1" in
      'created')
      if [ -f "$2" ] ; then
        try=''
        break
      fi
      ;;
      'removed')
      if [ ! -f "$2" ] ; then
        try=''
        break
      fi
      ;;
    esac
    echo -n .
    try=`expr $try + 1`
    sleep 1
  done
}
case "$1" in
  start)
    echo -n "Starting php-fpm "
    $php_fpm_BIN --daemonize $php_opts
    if [ "$?" != 0 ] ; then
      echo " failed"
      exit 1
    fi
    wait_for_pid created $php_fpm_PID
    if [ -n "$try" ] ; then
      echo " failed"
      exit 1
    else
      echo " done"
    fi
  ;;
  stop)
    echo -n "Gracefully shutting down php-fpm "
    if [ ! -r $php_fpm_PID ] ; then
      echo "warning, no pid file found - php-fpm is not running ?"
      exit 1
    fi
    kill -QUIT `cat $php_fpm_PID`
    wait_for_pid removed $php_fpm_PID
    if [ -n "$try" ] ; then
      echo " failed. Use force-quit"
      exit 1
    else
      echo " done"
    fi
  ;;
  status)
    if [ ! -r $php_fpm_PID ] ; then
      echo "php-fpm is stopped"
      exit 0
    fi
    PID=`cat $php_fpm_PID`
    if ps -p $PID | grep -q $PID; then
      echo "php-fpm (pid $PID) is running..."
    else
      echo "php-fpm dead but pid file exists"
    fi
  ;;
  force-quit)
    echo -n "Terminating php-fpm "
    if [ ! -r $php_fpm_PID ] ; then
      echo "warning, no pid file found - php-fpm is not running ?"
      exit 1
    fi
    kill -TERM `cat $php_fpm_PID`
    wait_for_pid removed $php_fpm_PID
    if [ -n "$try" ] ; then
      echo " failed"
      exit 1
    else
      echo " done"
    fi
  ;;
  restart)
    $0 stop
    $0 start
  ;;
  reload)
    echo -n "Reload service php-fpm "
    if [ ! -r $php_fpm_PID ] ; then
      echo "warning, no pid file found - php-fpm is not running ?"
      exit 1
    fi
    kill -USR2 `cat $php_fpm_PID`
    echo " done"
  ;;
  *)
    echo "Usage: $0 {start|stop|force-quit|restart|reload|status}"
    exit 1
  ;;
esac

添加权限加入chkconfig

chmod +x /etc/init.d/php-fpm
chkconfig --add php-fpm
pkill php-fpm
systemctl restart php-fpm

优化php命令路径

ln -s /usr/local/php7.4/bin/* /usr/bin
ln -s /usr/local/php7.4/sbin/* /usr/sbin

测试阶段

编辑php网页来测试lnmp架构环境的连通性和可行性
根据我上面的配置文件,我的网页目录是/var/www/html
创建nginx网页目录

mkdir -p /var/www/html
chown -R nginx.nginx /var/www/html

编写php网页

vim /var/www/html/index.php
-------------------------------------------
<?php
$servername = "localhost";
$username = "root";
$password = "123456";
try {
    $conn = new PDO("mysql:host=$servername;port=3306", $username, $password);
echo "mysql数据库连接成功!!!<br>";
}
catch(PDOException $e)
{
    echo $e->getMessage();
}
?>
<?php
echo "mysqli方式连接mysql数据库:";
$a=mysqli_connect("localhost","root","123456");
if($a){echo "数据库连接成功!!!";}else{echo "数据库连接失败!!!";}
?>
<?php
phpinfo();
?>

注意:大家根据自己的配置文件配置的网页路径加入网页要不然会404!!!

浏览器访问192.168.31.101,出现页面如下图:
lnmp.001
这样说明了lnmp架构搭建成功!!!

二、yum安装lnmp

#安装nginx,mariadb,php
yum -y install nginx php php-fpm php-mysql mariadb mariadb-server
#安装其他模块包
yum install -y php-devel php-common php-devel php-gd libjpeg* php-imap php-ldap php-odbc php-pear php-xml php-xmlrpc php-mbstring php-mcrypt php-bcmath php-mhash libmcrypt libmcrypt-devel
systemctl start nginx php-fpm mariadb
#初始化数据库
mysql_secure_installation

记得在nginx.conf配置加入支持php配置项:

location / {
    root   /var/www/html;
    index  index.html index.php;
}
location ~ \.php$ {
    root           /var/www/html;
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_index  index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include        fastcgi_params;
        }

注意:这里的网页目录根据自己的配置去设置

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值