新 VPS 快速初始化 (Ubuntu)
1. 系统更新
bashsudo apt update && sudo apt upgrade -y sudo apt autoremove -y
生产机可以开启自动安全更新
bashsudo apt install unattended-upgrades sudo dpkg-reconfigure unattended-upgrades
2. SSH 安全
修改配置
编辑 SSH 配置文件:
bashsudo vim /etc/ssh/sshd_config
推荐设置:
plaintextPermitRootLogin no PasswordAuthentication no # 如果用 key 登录 PubkeyAuthentication yes
重启 SSH:
bashsudo systemctl restart ssh
关闭密码登录前确保 SSH key 已能正常登录
3. 创建普通用户
避免长期使用 root:
bashadduser -m username usermod -aG sudo username passwd username
之后使用普通用户登录
4. 防火墙 (UFW)
开放常用端口:
bashsudo ufw allow OpenSSH sudo ufw allow 80 sudo ufw allow 443 sudo ufw enable
查看规则:
bashsudo ufw status sudo ufw status numbered # 示例输出 # Status: active # To Action From # [ 1] 80/tcp ALLOW Anywhere # [ 2] 443/tcp ALLOW Anywhere # [ 3] 9000/tcp ALLOW Anywhere # [ 4] 9001/tcp ALLOW Anywhere
删除规则:
bash# 按编号删除(删除后编号会变) sudo ufw delete 3 sudo ufw delete 3 # 或直接按端口删除 sudo ufw delete allow 9000/tcp sudo ufw delete allow 9001/tcp
5. 设置时区
默认多数 VPS 是 UTC
bashtimedatectl set-timezone Asia/Shanghai timedatectl
6. 安装常用工具
bashsudo apt install -y \ git curl wget vim btop unzip tar zsh \ build-essential ca-certificates golang
7. 检查系统资源
确认 VPS 配置是否正常:
bashlscpu # CPU 核心数 free -h # 内存 df -h # 磁盘 lsblk # 磁盘分区
8. 配置 Swap(内存 ≤ 2GB 推荐)
创建 2GB swap:
bashsudo fallocate -l 2G /swapfile sudo chmod 600 /swapfile sudo mkswap /swapfile sudo swapon /swapfile
开机自动挂载:
bashecho '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
9. 安装 fail2ban 防爆破
bashsudo apt install fail2ban
默认即可保护 SSH 爆破攻击。
10. 云厂商网络检查
确保安全组、防火墙和 VPC 已开放:
SSH
HTTP (80)
HTTPS (443)
否则服务可能无法访问外网。
11. 如果要跑服务
推荐安装容器工具:
bashsudo apt install podman # 或 Docker
额外优化建议
关闭 IPv6(如不使用)
设置 hostname
网络优化:开启 BBR
bashsudo tee /etc/sysctl.d/99-bbr.conf <<EOF net.core.default_qdisc = fq net.ipv4.tcp_congestion_control = bbr EOF sudo sysctl --system
验证:
bashsysctl net.ipv4.tcp_congestion_control lsmod | grep bbr
部署监控(如 node exporter、uptime)