如何管理VPS?

管理 Linux VPS 需要掌握基础的系统操作、安全设置、性能监控和日常维护。以下是关键步骤和技巧:

一、基础操作

  1. SSH 连接
    ssh username@your_vps_ip -p 端口号(默认22)
    • 使用密钥登录更安全(见下文)。
  2. 更新系统
    sudo apt update && sudo apt upgrade -y  # Debian/Ubuntu
    sudo yum update -y                     # CentOS/RHEL
  3. 用户管理
    • 创建新用户并授权:
      sudo adduser 用户名
      sudo usermod -aG sudo 用户名  # 赋予sudo权限

二、安全加固

  1. 配置防火墙
    • 使用 ufw(简单工具)或 iptables
      sudo ufw allow 22        # 开放SSH端口
      sudo ufw allow 80,443    # 开放HTTP/HTTPS
      sudo ufw enable
  2. 禁用密码登录(改用SSH密钥)
    • 生成密钥对(本地):
      ssh-keygen -t ed25519
    • 上传公钥到VPS:
      ssh-copy-id -i ~/.ssh/id_ed25519.pub 用户名@VPS_IP
    • 修改SSH配置(/etc/ssh/sshd_config):
      PasswordAuthentication no
      PermitRootLogin no
    • 重启服务:
      sudo systemctl restart sshd
  3. 安装 Fail2Ban(防暴力破解)
    sudo apt install fail2ban  # Debian/Ubuntu
    sudo yum install fail2ban  # CentOS

三、服务安装与配置

  1. Web服务器(Nginx/Apache)
    sudo apt install nginx    # 安装Nginx
    sudo systemctl start nginx
  2. 数据库(MySQL/MariaDB/PostgreSQL)
    sudo apt install mysql-server
    sudo mysql_secure_installation  # 安全初始化
  3. PHP(可选)
    sudo apt install php-fpm php-mysql

四、监控与维护

  1. 资源监控
    • 实时查看:
      top        # 基础监控
      htop       # 更友好的界面(需安装)
    • 磁盘空间:
      df -h
    • 网络流量:
      nload 或 iftop
  2. 日志管理
    • 查看日志:
      journalctl -u 服务名    # Systemd服务日志
      tail -f /var/log/nginx/access.log  # 实时跟踪

五、备份与恢复

  1. 自动备份
    • 使用 cron 定时任务 + rsync/tar
      # 示例:每天备份网站目录
      0 3 * * * tar -czvf /backup/website_$(date +\%F).tar.gz /var/www/html
  2. 数据库备份
    mysqldump -u 用户名 -p 数据库名 > backup.sql

六、常见维护技巧

  1. 计划任务(Cron)
    • 编辑任务:
      crontab -e
  2. 清理旧内核/缓存(Debian/Ubuntu)
    sudo apt autoremove
  3. 处理磁盘空间不足
    • 查找大文件:
      sudo du -sh /* | sort -rh

七、故障排查

  1. 服务无法启动
    • 查看日志:
      journalctl -u 服务名 --since "10 minutes ago"
  2. 网络问题
    ping VPS_IP
    traceroute VPS_IP
    sudo netstat -tulpn | grep LISTEN

八、优化建议

  1. 启用 Swap(内存不足时)
    sudo fallocate -l 2G /swapfile
    sudo chmod 600 /swapfile
    sudo mkswap /swapfile
    sudo swapon /swapfile
  2. 优化 Web 服务器
    • 配置缓存、启用 Gzip 压缩(Nginx/Apache)。

总结

  • 定期更新系统,及时修复漏洞。
  • 禁用不必要的服务,最小化攻击面。
  • 监控资源使用,避免超负荷运行。
  • 备份!备份!备份!

通过以上步骤,你可以高效且安全地管理 Linux VPS。遇到问题时,善用文档(man 命令)和社区资源(如 Stack Overflow)。

本站QQ群:806964688,discord群:https://discord.gg/YRNaXa4fgU