伺服器上架前,務必完成基礎優化與安全加固,降低攻擊面、釋放資源、建立可觀測基線。以下 7 項為生產環境最小必要動作清單。
四大必保服務:
- iptables/nftables/firewalld(防火牆)
- network/NetworkManager/systemd-networkd(網路)
- sshd(遠端管理生命線)
- rsyslog/systemd-journald(日誌審計基石)
檢查與關閉:
systemctl list-unit-files --state=enabled 列出所有啟用服務。
systemctl disable --now 關閉並停止非必要服務(如 postfix、chronyd(若用 ntpd)、avahi-daemon、cups、bluetooth 等)。
vi /etc/inittab
# 保留前 2 個(tty1, tty2),其餘註解
# 1:2345:respawn:/sbin/mingetty tty1
# 2:2345:respawn:/sbin/mingetty tty2
# 3:2345:respawn:/sbin/mingetty tty3 ← 註解
# ...
# 6:2345:respawn:/sbin/mingetty tty6 ← 註解
生效:init q(無需重開機)。
systemd 系統:systemctl disable getty@tty{3..6}.service。
vi /etc/selinux/config
SELINUX=disabled # 或 permissive
需重開機生效。建議:優先嘗試調整布林值/策略模組解決相容,保留 Enforcing 以獲得強制存取控制防護。
vi /etc/fstab
# 針對大量小檔案分區(/var/www、/data、/home 等)
/dev/mapper/vg00-lv_var /var ext4 defaults,noatime,nodiratime 0 0
效果:檔案讀取不再更新 atime,大幅降低 Web 伺服器、郵件伺服器、快取目錄的寫入 I/O。
# SysVinit
vi /etc/inittab
id:3:initdefault:
# systemd
systemctl set-default multi-user.target
省去 X11/Wayland、桌面環境數百 MB 記憶體與 CPU 佔用。
vi /etc/ssh/sshd_config
# 關鍵項
PermitRootLogin no # 禁止 Root 直接登入
PasswordAuthentication no # 強制金鑰認證
PubkeyAuthentication yes
X11Forwarding no # 不轉發 X11(省資源、減攻擊面)
UseDNS no # 關閉反向 DNS 解析(加快登入)
ClientAliveInterval 300 # 5 分鐘無操作發送保活
ClientAliveCountMax 2 # 2 次無回應斷線
MaxAuthTries 3 # 限制嘗試次數
AllowUsers adminuser@192.168.1.* # 限制允許登入的使用者與來源 IP
重啟:systemctl restart sshd。
vi /etc/profile
# 修改歷史記錄筆數
HISTSIZE=100
HISTFILESIZE=100
# 可選:忽略重複指令、以空白開頭的指令
HISTCONTROL=ignoreboth
# 即時寫入歷史(預設登出才寫入)
PROMPT_COMMAND="history -a; history -c; history -r"
生效:source /etc/profile。
dnf install dnf-automatic -y → 啟用 dnf-automatic.timer。auditctl -w /etc/passwd -p wa -k passwd_changes 監控關鍵檔案異動。timedatectl set-timezone Asia/Taipei、systemctl enable --now chronyd。完成上述 7 項,你的 Linux 伺服器已具備「精簡、可觀測、抗暴力破解、低 I/O 擾動」的生產級基線。後續再依應用層(資料庫、Web、容器)疊加專項優化。