logo 个人代码分享
性能优化

Linux 服务器性能调优

服务器性能调优是运维工作的重要环节,本文介绍常用的性能监控工具和优化技巧。

性能监控工具

在进行性能调优之前,首先需要了解服务器的当前状态。以下是常用的性能监控工具:

top / htop

top 是 Linux 系统自带的进程监控工具,htop 是其增强版本,提供更友好的界面:

# 安装 htop
yum install htop -y  # CentOS
apt install htop -y  # Ubuntu

# 运行 htop
htop

vmstat

vmstat 可以查看系统的虚拟内存、CPU、IO 等信息:

# 每秒刷新一次,共显示 5 次
vmstat 1 5

# 输出示例:
# procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
#  r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs  us sy id wa st
#  1  0      0 123456  65432 987654    0    0     0     0  100  200   5  2 93  0  0

iostat

iostat 用于监控系统 IO 设备的负载情况:

# 安装 sysstat
yum install sysstat -y

# 查看 IO 统计
iostat -x 1 5

CPU 优化

查看 CPU 信息

# 查看 CPU 核心数
nproc

# 查看 CPU 详细信息
lscpu

# 查看 CPU 使用率
top -bn1 | grep "Cpu(s)"

进程优先级调整

使用 nicerenice 调整进程优先级:

# 以低优先级运行进程
nice -n 10 ./my-script.sh

# 调整运行中进程的优先级
renice -n 10 -p <pid>

内存优化

查看内存使用情况

# 查看内存概览
free -h

# 查看详细的内存信息
cat /proc/meminfo

清理内存缓存

在某些情况下,可能需要手动清理内存缓存:

# 清理页面缓存
sync; echo 1 > /proc/sys/vm/drop_caches

# 清理目录项和 inode
sync; echo 2 > /proc/sys/vm/drop_caches

# 清理所有缓存
sync; echo 3 > /proc/sys/vm/drop_caches

磁盘 IO 优化

查看磁盘使用情况

# 查看磁盘空间
df -h

# 查看磁盘 IO 统计
iostat -x 1

# 查看哪些进程在进行 IO 操作
iotop

调整 IO 调度器

Linux 提供多种 IO 调度器,可以根据使用场景选择:

# 查看当前 IO 调度器
cat /sys/block/sda/queue/scheduler

# 临时修改 IO 调度器
echo deadline > /sys/block/sda/queue/scheduler

网络优化

TCP 参数调优

调整 TCP 参数可以提升网络性能:

# 编辑 /etc/sysctl.conf
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_max_tw_buckets = 5000

# 应用配置
sysctl -p

连接数限制

调整文件描述符限制:

# 查看当前限制
ulimit -n

# 临时修改限制
ulimit -n 65535

# 永久修改限制(编辑 /etc/security/limits.conf)
* soft nofile 65535
* hard nofile 65535

Nginx 性能优化

工作进程数

# 设置为 CPU 核心数
worker_processes auto;

# 每个进程的最大连接数
events {
    worker_connections 1024;
    use epoll;
    multi_accept on;
}

启用 Gzip 压缩

gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css application/javascript;

性能调优检查清单

  • 检查系统负载(uptime
  • 检查内存使用(free -h
  • 检查磁盘空间(df -h
  • 检查 IO 等待(iostat
  • 检查网络连接(netstat
  • 检查进程状态(ps aux