【Linux简单实用小命令025】一键优化Linux内核

Scroll Down

背景

在实际生产工作中,安装好一个Linux系统后,需要对Linux系统内核做一些优化,否则在运行高并发应用时会出现各种各样的问题。

编辑脚本

系统:centos 7.8。

查看命令:

 cat /etc/redhat-release 

编辑脚本:

vi sysconf.sh

#!/bin/bash
# author:姚毛毛

# 关闭SELinux
# 临时关闭
setenforce 0
# 修改文件关闭
sed -i 's/enforcing/disabled/g' /etc/selinux/config


# 加“\”不提示覆盖,/home/deploy/bin/sysconf 替换为.conf 文件路径
\cp -f /home/deploy/bin/sysconf/00-system.conf  /usr/lib/sysctl.d/

# 追加内核优化参数
cat >>  /etc/security/limits.conf  <<EOF
*           soft  core   unlimit
*           hard  core   unlimit
*           soft  fsize  unlimited
*           hard  fsize  unlimited
*           soft  data   unlimited
*           hard  data   unlimited
*           soft  nproc  65535
*           hard  nproc  63535
*           soft  stack  unlimited
*           hard  stack  unlimited

可以看到,上面有个覆盖的文件00-system.conf,其内容如下

# 关闭ipv6
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1

# 避免放大攻击
net.ipv4.icmp_echo_ignore_broadcasts = 1

# 开启恶意icmp错误消息保护
net.ipv4.icmp_ignore_bogus_error_responses = 1

#关闭路由转发
net.ipv4.ip_forward = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0

#开启反向路径过滤
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1

#处理无源路由的包
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0

#关闭sysrq功能
kernel.sysrq = 0

#core文件名中添加pid作为扩展名
kernel.core_uses_pid = 1

# 开启SYN洪水攻击保护
net.ipv4.tcp_syncookies = 1

#修改消息队列长度
kernel.msgmnb = 65536
kernel.msgmax = 65536

#设置最大内存共享段大小bytes
kernel.shmmax = 68719476736
kernel.shmall = 4294967296

#timewait的数量,默认180000
net.ipv4.tcp_max_tw_buckets = 6000
net.ipv4.tcp_sack = 1
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_rmem = 4096 87380 4194304
net.ipv4.tcp_wmem = 4096 16384 4194304
net.core.wmem_default = 8388608
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216

赋权、执行脚本

# 赋权
chmod +x *.sh

# 执行
./sysconf.sh