引言

CentOS 8作为企业级Linux发行版,以其稳定性、安全性和长期支持而受到广大系统管理员的青睐。本文将详细介绍CentOS 8系统的参数配置与优化,从基础配置到高级调优,帮助您打造一个安全、高效的服务器环境。通过合理的系统优化,可以显著提高服务器的性能、安全性和稳定性,满足不同业务场景的需求。

基础系统配置

系统更新与软件源配置

保持系统更新是确保服务器安全和稳定的第一步。CentOS 8使用DNF(Dandified YUM)作为包管理器,替代了之前版本中的YUM。

首先,检查并更新系统:

# 检查可用的更新 sudo dnf check-update # 更新系统 sudo dnf update -y # 安装EPEL(Extra Packages for Enterprise Linux)仓库 sudo dnf install -y epel-release 

配置国内镜像源可以显著提高软件包下载速度。以阿里云镜像源为例:

# 备份原有的repo文件 sudo cp -r /etc/yum.repos.d /etc/yum.repos.d.bak # 下载阿里云的CentOS 8 repo文件 sudo wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-8.repo # 清理缓存并生成新的缓存 sudo dnf clean all sudo dnf makecache 

主机名与网络配置

正确配置主机名和网络设置是服务器管理的基础。

# 查看当前主机名 hostnamectl # 设置静态主机名 sudo hostnamectl set-hostname server1.example.com # 配置网络接口(以ens33为例) sudo nmcli connection modify ens33 ipv4.addresses 192.168.1.100/24 sudo nmcli connection modify ens33 ipv4.gateway 192.168.1.1 sudo nmcli connection modify ens33 ipv4.dns "8.8.8.8 8.8.4.4" sudo nmcli connection modify ens33 ipv4.method manual sudo nmcli connection up ens33 

时区与时间同步

确保服务器时间准确对于日志记录、证书验证和许多其他服务至关重要。

# 查看当前时区 timedatectl # 设置时区为Asia/Shanghai sudo timedatectl set-timezone Asia/Shanghai # 安装并启用chrony(NTP客户端) sudo dnf install -y chrony sudo systemctl enable --now chronyd # 验证时间同步 chronyc tracking 

用户与权限管理

合理的用户权限管理是服务器安全的基础。

# 创建新用户 sudo useradd -m -s /bin/bash admin sudo passwd admin # 将用户添加到wheel组(授予sudo权限) sudo usermod -aG wheel admin # 禁用rootSSH登录 sudo sed -i 's/#PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config sudo systemctl restart sshd # 配置sudo免密码(可选) echo "admin ALL=(ALL) NOPASSWD: ALL" | sudo tee /etc/sudoers.d/admin 

系统性能优化

内核参数调优

通过调整内核参数,可以优化系统的网络、内存和I/O性能。创建自定义的内核参数配置文件:

sudo vi /etc/sysctl.d/99-custom.conf 

添加以下内容:

# 网络参数优化 net.core.rmem_max = 16777216 net.core.wmem_max = 16777216 net.ipv4.tcp_rmem = 4096 87380 16777216 net.ipv4.tcp_wmem = 4096 16384 16777216 net.ipv4.tcp_fin_timeout = 30 net.ipv4.tcp_keepalive_time = 1200 net.ipv4.tcp_max_syn_backlog = 8192 net.ipv4.tcp_tw_reuse = 1 net.ipv4.tcp_tw_recycle = 0 net.ipv4.ip_local_port_range = 10000 65000 net.ipv4.tcp_max_tw_buckets = 5000 # 文件系统优化 fs.file-max = 100000 fs.inotify.max_user_watches = 89100 # 内存管理优化 vm.swappiness = 10 vm.dirty_ratio = 60 vm.dirty_background_ratio = 2 

应用这些参数:

sudo sysctl -p /etc/sysctl.d/99-custom.conf 

文件系统优化

选择合适的文件系统并优化其参数可以提高I/O性能。

# 查看当前文件系统类型 df -T # 对于XFS文件系统(CentOS 8默认),可以优化挂载选项 sudo vi /etc/fstab 

修改挂载选项,例如:

UUID=xxxx-xxxx / xfs defaults,noatime,nodiratime 0 0 

重新挂载文件系统:

sudo mount -o remount / 

内存管理优化

优化内存管理可以提高系统性能,特别是在内存紧张的情况下。

# 创建swap文件(如果系统没有swap分区) sudo fallocate -l 2G /swapfile sudo chmod 600 /swapfile sudo mkswap /swapfile sudo swapon /swapfile echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab # 调整swap使用倾向(已在内核参数中设置swappiness=10) 

CPU调度优化

对于CPU密集型应用,可以调整CPU调度策略。

# 安装tuned(系统调优服务) sudo dnf install -y tuned sudo systemctl enable --now tuned # 查看可用的调优配置文件 sudo tuned-adm list # 应用吞吐量性能配置文件 sudo tuned-adm profile throughput-performance # 查看当前活动的配置文件 sudo tuned-adm active 

安全加固

防火墙配置

CentOS 8使用firewalld作为默认的防火墙管理工具。

# 检查firewalld状态 sudo firewall-cmd --state # 启动并启用firewalld sudo systemctl enable --now firewalld # 查看默认区域和活动区域 sudo firewall-cmd --get-default-zone sudo firewall-cmd --get-active-zones # 开放常用服务端口 sudo firewall-cmd --permanent --add-service=http sudo firewall-cmd --permanent --add-service=https sudo firewall-cmd --permanent --add-service=ssh # 或者开放特定端口 sudo firewall-cmd --permanent --add-port=8080/tcp # 重新加载防火墙配置 sudo firewall-cmd --reload # 查看开放的端口和服务 sudo firewall-cmd --list-all 

SELinux配置

SELinux(Security-Enhanced Linux)是CentOS中的强制访问控制(MAC)系统。

# 检查SELinux状态 getenforce # 设置SELinux为 enforcing模式(如果当前不是) sudo setenforce 1 sudo sed -i 's/SELINUX=permissive/SELINUX=enforcing/' /etc/selinux/config # 查看SELinux布尔值 sudo getsebool -a # 设置SELinux布尔值(例如允许HTTP连接到网络) sudo setsebool -P httpd_can_network_connect on # 查看和设置文件SELinux上下文 ls -Z /var/www/html/ sudo chcon -R -t httpd_sys_content_t /var/www/html/ 

服务安全配置

最小化服务暴露是提高服务器安全性的关键。

# 查看运行中的服务 systemctl list-units --type=service --state=running # 禁用不必要的服务 sudo systemctl disable --now postfix sudo systemctl disable --now avahi-daemon sudo systemctl disable --now telnet.socket # 安装并配置fail2ban防止暴力破解 sudo dnf install -y fail2ban sudo systemctl enable --now fail2ban # 创建SSH jail配置 sudo vi /etc/fail2ban/jail.local 

添加以下内容:

[sshd] enabled = true port = ssh filter = sshd logpath = /var/log/secure maxretry = 3 bantime = 3600 findtime = 600 

重启fail2ban服务:

sudo systemctl restart fail2ban 

系统审计与日志管理

配置系统审计和日志管理有助于安全监控和事件追踪。

# 安装并配置auditd sudo dnf install -y audit sudo systemctl enable --now auditd # 添加审计规则,监控文件修改 sudo auditctl -w /etc/passwd -p wa -k identity_modification sudo auditctl -w /etc/sudoers -p wa -k sudoers_modification # 永久保存审计规则 sudo vi /etc/audit/rules.d/audit.rules 

添加以下内容:

-w /etc/passwd -p wa -k identity_modification -w /etc/sudoers -p wa -k sudoers_modification 

配置日志轮转:

sudo vi /etc/logrotate.conf 

可以调整保留的日志文件数量和大小:

# rotate log files weekly weekly # keep 4 weeks worth of backlogs rotate 4 # compress old logs compress # delay compression delaycompress # create new (empty) log files after rotating old ones create # use date as a suffix of the rotated file dateext 

网络优化

网络参数调优

除了前面提到的内核参数,还可以进一步优化网络设置。

# 增加网络连接队列长度 echo 10000 | sudo tee /proc/sys/net/core/netdev_max_backlog # 启用TCP BBR拥塞控制算法(需要内核4.9+) echo 'net.core.default_qdisc=fq' | sudo tee -a /etc/sysctl.conf echo 'net.ipv4.tcp_congestion_control=bbr' | sudo tee -a /etc/sysctl.conf sudo sysctl -p # 验证BBR是否启用 sysctl net.ipv4.tcp_available_congestion_control 

高级网络配置

对于需要高级网络功能的服务器,可以配置网络绑定、VLAN或桥接。

# 安装网络绑定工具 sudo dnf install -y teamd # 创建网络绑定接口(以active-backup模式为例) sudo nmcli connection add type team con-name team0 ifname team0 config '{"runner": {"name": "activebackup"}}' sudo nmcli connection modify team0 ipv4.addresses 192.168.1.200/24 sudo nmcli connection modify team0 ipv4.gateway 192.168.1.1 sudo nmcli connection modify team0 ipv4.method manual # 添加物理接口到绑定 sudo nmcli connection add type team-slave con-name team0-port1 ifname ens33 master team0 sudo nmcli connection add type team-slave con-name team0-port2 ifname ens34 master team0 # 启用绑定接口 sudo nmcli connection up team0 

网络服务优化

针对常用的网络服务进行优化配置。

# SSH服务优化 sudo vi /etc/ssh/sshd_config 

修改以下参数:

# 禁用DNS查询以提高连接速度 UseDNS no # 仅使用协议2 Protocol 2 # 禁用空密码 PermitEmptyPasswords no # 设置MaxStartups参数防止暴力破解 MaxStartups 10:30:100 # 启用压缩以提高传输速度 Compression yes 

重启SSH服务:

sudo systemctl restart sshd 

服务优化

Web服务器优化

以Nginx为例,优化Web服务器配置。

# 安装Nginx sudo dnf install -y nginx sudo systemctl enable --now nginx # 优化Nginx配置 sudo vi /etc/nginx/nginx.conf 

修改以下参数:

user nginx; worker_processes auto; # 根据CPU核心数自动设置工作进程数 worker_rlimit_nofile 100000; # 增加文件描述符限制 events { worker_connections 4096; # 增加每个工作进程的最大连接数 use epoll; # 使用高效的epoll事件模型 multi_accept on; # 允许一个工作进程同时接受多个新连接 } http { # 基础优化 sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 30; keepalive_requests 100000; reset_timedout_connection on; client_body_timeout 10; send_timeout 2; # 缓冲区优化 client_body_buffer_size 128K; client_max_body_size 20m; client_header_buffer_size 1k; large_client_header_buffers 4 4k; output_buffers 1 32k; postpone_output 1460; # Gzip压缩 gzip on; gzip_disable "msie6"; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_min_length 1100; gzip_buffers 16 8k; gzip_http_version 1.1; gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript; } 

重启Nginx服务:

sudo systemctl restart nginx 

数据库优化

以MySQL/MariaDB为例,优化数据库配置。

# 安装MariaDB sudo dnf install -y mariadb-server sudo systemctl enable --now mariadb # 安全初始化 sudo mysql_secure_installation # 优化MariaDB配置 sudo vi /etc/my.cnf.d/mariadb-server.cnf 

在[mysqld]部分添加以下内容:

# 基础优化 innodb_buffer_pool_size = 2G # 设置为可用内存的50-70% innodb_log_file_size = 256M innodb_log_buffer_size = 64M innodb_flush_log_at_trx_commit = 2 # 平衡性能和数据安全 innodb_flush_method = O_DIRECT innodb_file_per_table = 1 # 连接优化 max_connections = 200 max_connect_errors = 100000 thread_cache_size = 32 wait_timeout = 300 # 查询缓存优化(MySQL 8.0之前版本) query_cache_type = 1 query_cache_size = 128M query_cache_limit = 4M # 表缓存 table_open_cache = 2048 table_definition_cache = 1024 # 临时表 tmp_table_size = 256M max_heap_table_size = 256M # 其他优化 sort_buffer_size = 4M read_buffer_size = 3M read_rnd_buffer_size = 4M join_buffer_size = 4M 

重启MariaDB服务:

sudo systemctl restart mariadb 

缓存服务优化

安装和优化Redis作为缓存服务。

# 安装Redis sudo dnf install -y redis sudo systemctl enable --now redis # 优化Redis配置 sudo vi /etc/redis.conf 

修改以下参数:

# 内存设置 maxmemory 512mb # 根据可用内存设置 maxmemory-policy allkeys-lru # 内存淘汰策略 # 持久化设置 save 900 1 # 900秒内至少有1个key改变则保存 save 300 10 # 300秒内至少有10个key改变则保存 save 60 10000 # 60秒内至少有10000个key改变则保存 # 网络设置 tcp-keepalive 60 # TCP保持活跃的时间 tcp-backlog 511 # TCP监听队列长度 # 日志设置 loglevel notice # 日志级别 

重启Redis服务:

sudo systemctl restart redis 

监控与维护

系统监控工具

安装和配置系统监控工具,以便及时发现和解决问题。

# 安装基础监控工具 sudo dnf install -y htop iotop iftop nethogs sysstat # 安装Prometheus和Grafana进行高级监控 # 添加Prometheus仓库 sudo tee /etc/yum.repos.d/prometheus.repo <<EOF [prometheus] name=Prometheus baseurl=https://packages.cloud.google.com/yum/repos/prometheus-el7 enabled=1 gpgcheck=0 EOF # 安装Prometheus和Node Exporter sudo dnf install -y prometheus node_exporter sudo systemctl enable --now prometheus node_exporter # 安装Grafana sudo tee /etc/yum.repos.d/grafana.repo <<EOF [grafana] name=grafana baseurl=https://packages.grafana.com/oss/rpm repo_gpgcheck=1 enabled=1 gpgcheck=1 gpgkey=https://packages.grafana.com/gpg.key sslverify=1 sslcacert=/etc/pki/tls/certs/ca-bundle.crt EOF sudo dnf install -y grafana sudo systemctl enable --now grafana-server 

性能分析

使用工具进行系统性能分析。

# 使用vmstat监控系统资源使用情况 vmstat 1 10 # 使用iostat监控I/O性能 iostat -xz 1 10 # 使用sar收集系统活动数据 sar -u 1 10 # CPU使用率 sar -r 1 10 # 内存使用率 sar -b 1 10 # I/O传输率 # 使用perf进行性能分析 sudo dnf install -y perf perf top # 实时显示最消耗CPU的函数 

自动化维护

设置自动化维护任务,确保系统持续稳定运行。

# 创建日志清理脚本 sudo vi /usr/local/bin/clean_logs.sh 

添加以下内容:

#!/bin/bash # 清理30天前的日志 find /var/log -type f -name "*.log.*" -mtime +30 -delete # 清理临时文件 find /tmp -type f -atime +10 -delete # 清理用户会话 find /tmp -type s -name "session_*" -mtime +1 -delete # 清理旧内核(保留最近2个) dnf remove $(dnf repoquery --installonly --latest-limit=-2 -q) 

设置脚本可执行:

sudo chmod +x /usr/local/bin/clean_logs.sh 

添加到crontab:

sudo crontab -e 

添加以下内容:

# 每周日凌晨3点执行清理任务 0 3 * * 0 /usr/local/bin/clean_logs.sh 

总结

本文详细介绍了CentOS 8系统的参数配置与优化,从基础系统配置到高级性能调优,涵盖了系统性能优化、安全加固、网络优化、服务优化以及监控与维护等多个方面。通过合理配置这些参数,您可以打造一个安全、高效、稳定的服务器环境,满足不同业务场景的需求。

需要注意的是,系统优化是一个持续的过程,需要根据实际业务需求和服务器负载情况进行调整。在进行任何重大更改之前,建议先在测试环境中验证,并做好备份。同时,定期监控系统性能,及时发现并解决问题,是确保服务器长期稳定运行的关键。

希望本文能为您提供有价值的参考,帮助您更好地管理和优化CentOS 8服务器系统。