解决 CentOS 7 报错: Cannot find a valid baseurl for repo extras7x86_64

操作环境

[root@localhost ~]# cat /etc/redhat-release 
CentOS Linux release 7.5.1804 (Core)

报错详情

我在虚拟化软件中使用最小化安装的方式安装了 CentOS 7, 安装完成后, 在配置本地 yum 源时, 当执行 yum makecache 生成软件包的本地缓存时产生了如下报错:

[root@localhost ~]# yum makecache
已加载插件:fastestmirror
Determining fastest mirrors
Could not retrieve mirrorlist http://mirrorlist.centos.org/?release=7&arch=x86_64&repo=extras&infra=stock error was
14: curl#6 - "Could not resolve host: mirrorlist.centos.org; 未知的错误"


 One of the configured repositories failed (未知),
 and yum doesn't have enough cached data to continue. At this point the only
 safe thing yum can do is fail. There are a few ways to work "fix" this:

     1. Contact the upstream for the repository and get them to fix the problem.

     2. Reconfigure the baseurl/etc. for the repository, to point to a working
        upstream. This is most often useful if you are using a newer
        distribution release than is supported by the repository (and the
        packages for the previous distribution release still work).

     3. Run the command with the repository temporarily disabled
            yum --disablerepo=<repoid> ...

     4. Disable the repository permanently, so yum won't use it by default. Yum
        will then just ignore the repository until you permanently enable it
        again or use --enablerepo for temporary usage:

            yum-config-manager --disable <repoid>
        or
            subscription-manager repos --disable=<repoid>

     5. Configure the failing repository to be skipped, if it is unavailable.
        Note that yum will try to contact the repo. when it runs most commands,
        so will have to try and fail each time (and thus. yum will be be much
        slower). If it is a very temporary problem though, this is often a nice
        compromise:

            yum-config-manager --save --setopt=<repoid>.skip_if_unavailable=true

Cannot find a valid baseurl for repo: extras/7/x86_64

报错分析

报错中提到 “Could not retrieve mirrorlist…(不能检索镜像列表…)”, 既然不能检索, 那么我们就查看一下是否能 ping 通该镜像列表的地址:

[root@localhost ~]# ping mirrorlist.centos.org
ping: mirrorlist.centos.org: 未知的名称或服务

结果显示 ping 不通, 而且根据提示, 报错很可能是由于没有配置 DNS 服务器 (“未知的名称或服务”) 导致的, 由于直接 ping IP 地址可以通, 所以该系统是已经连接上互联网的 (基本可以判定是 DNS 解析的问题):

[root@localhost ~]# ping 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=128 time=65.9 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=128 time=64.8 ms
^Z
[1]+  已停止               ping 8.8.8.8

经过分析, 产生该报错的一个原因是没有配置 DNS 服务器, 导致系统无法对 yum 源中的域名进行解析, 进而认为无法连接到 yum 源中的镜像服务器, 从而发出报错.

解决方案

编辑 CentOS 7 的 DNS 配置文件:

vi /etc/resolv.conf

写入:

nameserver 8.8.8.8

之后重启系统或者重启网络即可.

重启网络方式 1:

[root@localhost ~]# service network restart
Restarting network (via systemctl):                        [  确定  ]

重启网络方式 2:

[root@localhost ~]# systemctl restart network
[root@localhost ~]#

至此, 问题解决.