2. 安装必要的工具
首先,更新系统并安装一些必要的工具:
yum update -y
yum install -y wget vim
3. 编写一键部署脚本
创建一个名为 lnmp_install.sh 的脚本文件:
vim lnmp_install.sh
#!/bin/bash
# 定义颜色变量
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # No Color
# 安装 Nginx
install_nginx() {
echo -e "${YELLOW}正在安装 Nginx...${NC}"
yum install -y epel-release
yum install -y nginx
systemctl start nginx
systemctl enable nginx
if [ $? -eq 0 ]; then
echo -e "${GREEN}Nginx 安装并启动成功!${NC}"
else
echo -e "${RED}Nginx 安装或启动失败!${NC}"
exit 1
fi
}
# 安装 MySQL(使用 MariaDB,CentOS 7 默认的 MySQL 替代品)
install_mysql() {
echo -e "${YELLOW}正在安装 MariaDB...${NC}"
yum install -y mariadb-server mariadb
systemctl start mariadb
systemctl enable mariadb
if [ $? -eq 0 ]; then
echo -e "${GREEN}MariaDB 安装并启动成功!${NC}"
# 进行安全设置
mysql_secure_installation
else
echo -e "${RED}MariaDB 安装或启动失败!${NC}"
exit 1
fi
}
# 安装 PHP 及相关扩展
install_php() {
echo -e "${YELLOW}正在安装 PHP 及相关扩展...${NC}"
yum install -y http://rpms.remirepo.net/enterprise/remi-release-7.rpm
yum install -y yum-utils
yum-config-manager --enable remi-php74
yum install -y php-fpm php-mysqlnd php-mbstring php-xml
systemctl start php-fpm
systemctl enable php-fpm
if [ $? -eq 0 ]; then
echo -e "${GREEN}PHP 及相关扩展安装并启动成功!${NC}"
else
echo -e "${RED}PHP 及相关扩展安装或启动失败!${NC}"
exit 1
fi
}
# 配置 Nginx 支持 PHP
configure_nginx_php() {
echo -e "${YELLOW}正在配置 Nginx 支持 PHP...${NC}"
cat > /etc/nginx/conf.d/php.conf << EOF
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
index index.php index.html index.htm;
location / {
try_files \$uri \$uri/ /index.php?\$query_string;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
include fastcgi_params;
}
}
EOF
systemctl restart nginx
if [ $? -eq 0 ]; then
echo -e "${GREEN}Nginx 配置 PHP 成功!${NC}"
else
echo -e "${RED}Nginx 配置 PHP 失败!${NC}"
exit 1
fi
}
# 创建测试 PHP 文件
create_test_php_file() {
echo -e "${YELLOW}正在创建测试 PHP 文件...${NC}"
cat > /usr/share/nginx/html/info.php << EOF
<?php
phpinfo();
?>
EOF
echo -e "${GREEN}测试 PHP 文件创建成功!请访问 http://服务器IP/info.php 进行测试。${NC}"
}
# 主函数
main() {
install_nginx
install_mysql
install_php
configure_nginx_php
create_test_php_file
}
# 执行主函数
main
4. 给脚本添加执行权限
chmod +x lnmp_install.sh
5. 执行一键部署脚本
./lnmp_install.sh