跳到主要内容

Debian apt 添加阿里源

· 阅读需 4 分钟

新装的 Debian 默认走官方源,在国内下载软件包经常只有几十 KB/s,装个东西半天卡在进度条上。把 apt 源换成阿里云的国内镜像,是拿到机器后我一般会做的第一件事,这里把步骤和注意点记一下。

为什么要换源

apt 安装软件时,会从 /etc/apt/sources.list 里配置的仓库地址下载包和索引。官方源的服务器在境外,国内访问延迟高、带宽小,apt-get updateapt-get install 都会很慢,甚至超时失败。阿里云、清华、中科大等镜像站会定期从官方源同步完整仓库,包内容一致,只是地址换成了国内节点,速度能有量级的提升。

源列表的格式

动手之前先看懂 sources.list 里每一行的含义,格式是固定的:

deb [仓库地址] [发行版代号] [组件...]
  • deb 表示二进制包仓库,deb-src 是对应的源码仓库,平时只装软件的话 deb-src 不配也可以;
  • 发行版代号对应 Debian 的版本,比如 stretch 就是 Debian 9,换源时代号必须和自己系统的版本一致,可以用 cat /etc/os-release 确认;
  • 组件里 main 是官方主仓库,contribnon-free 包含依赖非自由软件或本身非自由的包,比如一些驱动和固件,一般都带上;
  • stretch/updates 是安全更新仓库,stretch-updates 是常规更新,stretch-backports 提供从新版本移植回来的软件包。

操作步骤

1)进入源文件列表

vim /etc/apt/sources.list

改之前建议先备份一份,出问题可以直接还原:

# 备份原有源配置
cp /etc/apt/sources.list /etc/apt/sources.list.bak

# 编辑源列表
vim /etc/apt/sources.list

2)添加阿里源地址

把原有内容注释掉或清空,写入下面几行(以 stretch 即 Debian 9 为例):

deb http://mirrors.aliyun.com/debian/ stretch main non-free contrib
deb-src http://mirrors.aliyun.com/debian/ stretch main non-free contrib
deb http://mirrors.aliyun.com/debian-security stretch/updates main
deb-src http://mirrors.aliyun.com/debian-security stretch/updates main
deb http://mirrors.aliyun.com/debian/ stretch-updates main non-free contrib
deb-src http://mirrors.aliyun.com/debian/ stretch-updates main non-free contrib
deb http://mirrors.aliyun.com/debian/ stretch-backports main non-free contrib
deb-src http://mirrors.aliyun.com/debian/ stretch-backports main non-free contrib

方便复制的纯文本版本:

deb http://mirrors.aliyun.com/debian/ stretch main non-free contrib
deb-src http://mirrors.aliyun.com/debian/ stretch main non-free contrib
deb http://mirrors.aliyun.com/debian-security stretch/updates main
deb-src http://mirrors.aliyun.com/debian-security stretch/updates main
deb http://mirrors.aliyun.com/debian/ stretch-updates main non-free contrib
deb-src http://mirrors.aliyun.com/debian/ stretch-updates main non-free contrib
deb http://mirrors.aliyun.com/debian/ stretch-backports main non-free contrib
deb-src http://mirrors.aliyun.com/debian/ stretch-backports main non-free contrib

3)更新源

保存退出后刷新本地的包索引,让新配置生效:

apt-get update

这一步会从阿里源重新拉取所有仓库的索引文件,输出里应该能看到 mirrors.aliyun.com 的地址。之后再执行 apt-get install,下载就走国内镜像了。

踩坑与注意

  • 代号一定要和系统版本对应。把 stretch 的源写到别的版本上,轻则 update 报 404,重则混装不同版本的包把依赖搞乱。其他版本只需把上面所有 stretch 换成对应代号。
  • 较新的 Debian 版本里,安全源的写法从 代号/updates 改成了 代号-security,照抄旧文章会遇到找不到仓库的报错,以镜像站首页给出的配置为准。
  • 如果 update 时报 GPG 签名相关的错误,通常是缺少对应的密钥或系统时间不对,先检查时间再排查密钥,不要用跳过验证的方式硬装。
  • 内网或对稳定性要求高的环境,改完源后可以先 apt-get update 加装一个小包验证一下,确认没问题再做大规模安装或升级。

小结

换源本身就三步:备份并编辑 /etc/apt/sources.list,写入镜像地址,apt-get update 刷新索引。关键在于代号和系统版本要对得上,改前留好备份,出问题随时能退回去。这套思路对清华源、中科大源同样适用,换个域名而已。

评论 / COMMENTS