在阿里云上运行Web服务时,针对Ubuntu Server的系统优化建议如下:
一、系统基础优化
-
更新系统与内核
sudo apt update && sudo apt upgrade -y # 可选:安装LTS内核的HWE版本(适用于长期支持版) sudo apt install --install-recommends linux-generic-hwe-22.04 -
时区与时间同步
sudo timedatectl set-timezone Asia/Shanghai sudo apt install chrony -y sudo systemctl enable chrony -
配置阿里云镜像源
- 使用阿里云提供的Ubuntu镜像提速软件包下载。
二、内核参数优化
-
调整网络参数(
/etc/sysctl.conf)# 提升连接数和性能 net.core.somaxconn = 65535 net.ipv4.tcp_max_syn_backlog = 65535 net.ipv4.tcp_tw_reuse = 1 net.ipv4.tcp_fin_timeout = 30 # 减少TCP Keepalive时间 net.ipv4.tcp_keepalive_time = 600 net.ipv4.tcp_keepalive_intvl = 30 # 内存与缓冲区优化 net.core.rmem_max = 67108864 net.core.wmem_max = 67108864 net.ipv4.tcp_rmem = 4096 87380 67108864 net.ipv4.tcp_wmem = 4096 65536 67108864sudo sysctl -p -
文件描述符限制(
/etc/security/limits.conf)* soft nofile 65535 * hard nofile 65535 * soft nproc 65535 * hard nproc 65535
三、Web服务专项优化
-
Nginx/Apache配置
- Nginx示例:
worker_processes auto; worker_rlimit_nofile 65535; events { worker_connections 65535; use epoll; } - 启用Gzip压缩、静态缓存,根据业务调整超时时间。
- Nginx示例:
-
PHP优化(如使用PHP-FPM)
- 调整
pm.max_children、pm.start_servers等参数(根据内存动态计算)。 - 启用OPcache提速。
- 调整
-
数据库优化(如MySQL/PostgreSQL)
- 调整InnoDB缓冲池大小(建议为可用内存的70%-80%)。
- 启用查询缓存或调整连接数(需根据业务负载测试)。
四、安全加固
-
SSH安全
# 修改默认端口,禁用root登录 sudo sed -i 's/#Port 22/Port 你的端口/' /etc/ssh/sshd_config sudo sed -i 's/PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config sudo systemctl restart sshd -
防火墙配置
sudo ufw enable sudo ufw allow 你的SSH端口 sudo ufw allow 80/tcp sudo ufw allow 443/tcp -
安装基础安全工具
sudo apt install fail2ban -y # 防暴力破解 sudo apt install unattended-upgrades -y # 自动安全更新
五、资源监控与日志
-
安装监控组件
- 使用阿里云云监控Agent:
wget http://cloudmonitor-agent.oss-cn-hangzhou.aliyuncs.com/linux/cloudmonitor-agent-linux-x64.tar.gz tar -xzf cloudmonitor-agent-linux-x64.tar.gz cd cloudmonitor-agent sudo ./install.sh
- 使用阿里云云监控Agent:
-
日志轮转
- 配置
logrotate避免日志占满磁盘:sudo apt install logrotate # 根据业务配置/etc/logrotate.d/自定义规则
- 配置
六、存储与磁盘优化
-
使用高效云盘
- Web服务建议选择ESSD云盘,并根据IOPS需求选择性能级别。
-
文件系统优化
# 调整ext4挂载参数(/etc/fstab) defaults,noatime,nodiratime,discard # 添加noatime和discard(SSD适用) -
临时文件挂载tmpfs
# /etc/fstab 添加(适用于频繁读写的小文件) tmpfs /tmp tmpfs defaults,noatime,size=1G 0 0
七、备份与快照
- 定期备份
- 使用阿里云快照功能创建系统盘和数据盘定期快照。
- 重要配置文件可备份至OSS。
八、其他建议
-
选择合适实例规格
- Web应用:通用型g7或计算型c7。
- 高网络包量:选择高网络性能实例(如
g7ne)。 - 启用弹性伸缩(SLB+伸缩组)应对流量波动。
-
启用阿里云DDoS高防/WAF(若面向公网)。
注意事项
- 所有优化需结合实际业务压力测试调整。
- 修改内核参数前建议备份原配置。
- 数据库优化需根据具体版本和存储引擎调整。
通过以上优化,可显著提升Ubuntu Server在阿里云上运行Web服务的性能、安全性和稳定性。
CLOUD技术笔记