搬瓦工 VPS 位于海外机房,访问官方软件源(如 Debian/Ubuntu 的默认源或 CentOS 的官方源)时速度可能较慢。更换为国内镜像源能显著提升 apt update 和软件安装速度。本文分别介绍 Debian/Ubuntu 和 CentOS/AlmaLinux 的换源方法。

本文要点

  • 备份现有 sources.list
  • 替换为国内镜像地址
  • 运行 apt update 验证
  • CentOS/AlmaLinux yum/dnf 换源方法

换源适用场景说明

换源对 VPS 本身位于中国大陆的服务器效果最明显。若你的搬瓦工 VPS 机房在海外,访问国内镜像源的速度未必优于官方源,可先对比实际速度再决定是否更换。

Debian/Ubuntu 换源

第一步:备份原有配置

cp /etc/apt/sources.list /etc/apt/sources.list.bak

第二步:替换为镜像源

以 Debian 12(bookworm)更换为阿里云镜像为例:

cat > /etc/apt/sources.list << 'EOF'
deb https://mirrors.aliyun.com/debian/ bookworm main contrib non-free non-free-firmware
deb https://mirrors.aliyun.com/debian/ bookworm-updates main contrib non-free non-free-firmware
deb https://mirrors.aliyun.com/debian-security/ bookworm-security main contrib non-free non-free-firmware
EOF

Ubuntu 22.04(jammy)换源示例:

cat > /etc/apt/sources.list << 'EOF'
deb https://mirrors.aliyun.com/ubuntu/ jammy main restricted universe multiverse
deb https://mirrors.aliyun.com/ubuntu/ jammy-updates main restricted universe multiverse
deb https://mirrors.aliyun.com/ubuntu/ jammy-security main restricted universe multiverse
EOF

第三步:更新软件包索引

apt update

若无报错,换源成功。安装速度会明显提升。

常用国内镜像源对比

镜像站地址前缀特点
阿里云mirrors.aliyun.com速度快、稳定,覆盖广
腾讯云mirrors.tencent.com速度快、同步及时
中科大mirrors.ustc.edu.cn老牌高校镜像,稳定
清华大学mirrors.tuna.tsinghua.edu.cn老牌高校镜像,资源齐全

发行版版本代号要对应

sources.list 中的版本代号(如 bookworm、jammy)必须与你的系统版本一致。用 lsb_release -cs 可以查看当前系统的版本代号。

CentOS/AlmaLinux 换源

CentOS 及其替代版本(AlmaLinux、Rocky Linux)使用 dnf/yum,配置文件位于 /etc/yum.repos.d/

备份并替换(AlmaLinux 8/9 示例)

# 备份
mkdir -p /etc/yum.repos.d/backup
mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/backup/

# 下载阿里云镜像配置
curl -o /etc/yum.repos.d/aliyun.repo \
  https://mirrors.aliyun.com/repo/aliyuncs-8.repo

# 刷新缓存
dnf makecache

切换后先验证

换源后执行 dnf update --checkapt list --upgradable 查看是否能正常获取更新列表,确认镜像源工作正常再安装软件。

换源失败时的恢复方法

如果换源后出现报错,可从备份恢复:

# Debian/Ubuntu
cp /etc/apt/sources.list.bak /etc/apt/sources.list
apt update

# CentOS/AlmaLinux
mv /etc/yum.repos.d/backup/*.repo /etc/yum.repos.d/
dnf makecache

小结

  • 换源前先备份 sources.list 或 .repo 文件
  • 版本代号(bookworm/jammy 等)必须与系统一致
  • apt update / dnf makecache 验证换源结果
  • 出问题从备份快速恢复

常见问题

换源后 apt update 报 404 错误怎么办?

通常是版本代号填错。用 lsb_release -cs 查看系统代号,确保 sources.list 中的代号与之完全一致。

海外 VPS 换国内镜像源有意义吗?

取决于你和 VPS 之间以及 VPS 到镜像站之间的网络情况。可以先测速对比,若国内镜像源更快则换,否则保持默认。

换源后之前安装的软件会受影响吗?

不会。换源只影响新的软件包下载来源,已安装的软件正常运行,下次更新时从新源获取。