Skip to content

Linux apt / yum 换国内镜像源加速

apt update / yum install 慢、超时,是因为默认用海外官方源。换成国内镜像立竿见影。下面按发行版分别说明。

先备份

改源前务必备份原文件,改错了能还原。每节都给了备份命令。

一、Ubuntu(传统 sources.list,22.04 及更早)

bash
# 备份
sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak

# 用 sed 一键替换为阿里云(其他镜像同理换域名)
sudo sed -i 's@//.*archive.ubuntu.com@//mirrors.aliyun.com@g; s@//.*security.ubuntu.com@//mirrors.aliyun.com@g' /etc/apt/sources.list

sudo apt update

二、Ubuntu 24.04+(新版 DEB822 格式)

Ubuntu 24.04 起软件源在 /etc/apt/sources.list.d/ubuntu.sources:

bash
sudo cp /etc/apt/sources.list.d/ubuntu.sources /etc/apt/sources.list.d/ubuntu.sources.bak
sudo sed -i 's@//.*archive.ubuntu.com@//mirrors.aliyun.com@g; s@//.*security.ubuntu.com@//mirrors.aliyun.com@g' /etc/apt/sources.list.d/ubuntu.sources
sudo apt update

三、Debian

bash
sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak
sudo sed -i 's@//.*deb.debian.org@//mirrors.aliyun.com@g; s@//.*security.debian.org@//mirrors.aliyun.com@g' /etc/apt/sources.list
sudo apt update

四、CentOS / RHEL(yum / dnf)

CentOS 7 示例(用阿里云官方脚本最省事):

bash
# 备份
sudo mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.bak

# 下载阿里云的 repo 文件
sudo curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo

# 重建缓存
sudo yum clean all && sudo yum makecache

CentOS 8 / Stream 的官方源已变动,建议直接用阿里云对应版本的 repo,或迁移到 Rocky/Alma Linux 并用其国内镜像。

五、常用镜像域名

镜像apt/yum 域名
阿里云mirrors.aliyun.com
清华 TUNAmirrors.tuna.tsinghua.edu.cn
中科大mirrors.ustc.edu.cn
腾讯云mirrors.cloud.tencent.com

把上面命令里的 mirrors.aliyun.com 换成任一即可。

六、还原官方源

bash
# apt
sudo mv /etc/apt/sources.list.bak /etc/apt/sources.list && sudo apt update
# yum
sudo mv /etc/yum.repos.d/CentOS-Base.repo.bak /etc/yum.repos.d/CentOS-Base.repo && sudo yum makecache

常见问题

Q:换源后 apt update 报 GPG / NO_PUBKEY? 镜像同步或密钥问题,sudo apt update 重试;必要时导入对应公钥。

Q:docker 容器里也慢? 容器内同样可改源,或用带国内源的基础镜像;拉镜像本身慢见 Docker 加速

小结

  • 认准发行版对应的源文件位置(注意 Ubuntu 24.04 换了新格式)。
  • 改前必备份,一条 sed 搞定替换。
  • 阿里云 / 清华 / 中科大任选,速度都不错。

本文仅供技术学习与研究,请遵守所在国家/地区法律法规。

本站为技术学习交流站点,与 GitHub, Inc. 无任何隶属或官方关系。所有内容仅供技术研究与学习,请遵守所在国家/地区的法律法规。