跳到主要内容

Linux

2024年07月29日
柏拉文
越努力,越幸运

一、认识


二、脚本


1. 创建一个名为 install_nginx.sh 的脚本

#!/bin/bash

set -e # 遇到错误时停止脚本执行

# 定义变量
FIREWALL_SERVICE_HTTP="http"
FIREWALL_SERVICE_HTTPS="https"
NGINX_REPO_FILE="/etc/yum.repos.d/nginx.repo"
NGINX_REPO_URL="https://nginx.org/packages/centos/8/x86_64/"
NGINX_GPG_KEY_URL="https://nginx.org/keys/nginx_signing.key"


# 1. 删除旧版本 Nginx(如果存在)
echo "Removing old versions of Nginx..."
if sudo yum list installed | grep -q '^nginx'; then
sudo yum remove -y nginx || true
else
echo "No old Nginx versions detected."
fi

# 2. 安装必要的系统工具
echo "Installing required packages..."
sudo yum install -y epel-release yum-utils

# 3. 添加 Nginx 软件源
echo "Adding Nginx repository..."
if [ ! -f "$NGINX_REPO_FILE" ]; then
sudo tee "$NGINX_REPO_FILE" > /dev/null <<EOF
[nginx]
name=nginx repo
baseurl=$NGINX_REPO_URL
gpgcheck=1
enabled=1
gpgkey=$NGINX_GPG_KEY_URL
EOF
else
echo "Nginx repository already exists."
fi

# 4. 更新软件源缓存并安装 Nginx
echo "Updating package index and installing Nginx..."
sudo yum makecache
sudo yum install -y nginx

# 5. 启动 Nginx 服务
echo "启动 Nginx 服务"
sudo systemctl start nginx
echo "重启时自动启动 Nginx 服务"
sudo systemctl enable nginx

# 6. 配置 Nginx 默认站点(可选)
echo "Configuring default Nginx site..."
DEFAULT_CONF="/etc/nginx/conf.d/default.conf"
if [ ! -f "$DEFAULT_CONF" ]; then
sudo tee "$DEFAULT_CONF" > /dev/null <<EOF
server {
listen 80;
server_name localhost;

location / {
root /usr/share/nginx/html;
index index.html index.htm;
}

error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
EOF
echo "Default Nginx site configuration added."
else
echo "Default Nginx site configuration already exists."
fi

# 7. 验证 Nginx 安装
echo "Verifying Nginx installation..."
if curl -I http://localhost | grep -q "200 OK"; then
echo "Nginx is successfully installed and running."
else
echo "Nginx installation verification failed."
exit 1
fi

echo "Nginx installation completed successfully!"

2. 发送 install_nginx.sh 脚本(可选)

scp install_nginx.sh root@192.168.105.132:/root

3. 赋予脚本可执行权限

chmod +x install_nginx.sh

4. 执行脚本,安装 Nginx

./install_nginx.sh

5. 检查 Nginx 服务状态

systemctl start nginx // 立即启动 nginx 服务,而不是等到系统重启时。
systemctl stop nginx // 停止正在运行的 nginx 服务。
systemctl disable nginx // 禁止 nginx 服务在系统启动时自动启动。
systemctl status nginx // 查看 nginx 服务的当前状态。
systemctl list-unit-files --type=service | grep enabled // 查看所有自动启动的服务