最近在學習Docker,系統環境是CentOS7
1. 下載下傳緩慢
在使用Dockerfile建立Docker鏡像時,引用基礎鏡像和yum安裝都很緩慢。Dockerfile内容如下:
[[email protected] static_web]$ cat Dockerfile
# Version: 0.0.1
FROM centos:7.7.1908
MAINTAINER kanou "[email protected]"
RUN yum update -y && yum install -y epel-release
RUN yum install -y nginx
#RUN echo 'Hi, I am in your container' > /usr/share/nginx/html/index.html
EXPOSE 80
2. 分析原因
由于預設Docker基礎鏡像源及yum源都是連接配接國外的位址,在國内通路會比較緩慢。
3. 解決方法
修改Dockerfile中基礎鏡像CentOS7的鏡像加速器和yum源,但在Dockerfile要對這兩個内容進行修改比較麻煩,
于是想到先在本地CentOS7系統先将鏡像加速器和yum源的配置檔案先修改好并拷貝到Dockerfile的上下文目錄中,
在Dockerfile中将本地配置檔案拷貝到Dockerfile的目标基礎鏡像中,達到修改目标基礎鏡像的加速器和yum源的目的。
操作步驟如下:
(1)修改基礎鏡像加速器,因為這些使用的是CentOS7,CentOS7可以通過修改daemon配置檔案/etc/docker/daemon.json來使用加速器:\
sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
"registry-mirrors": ["https://9an8eogo.mirror.aliyuncs.com"]
}
EOF
将修改好的 daemon.json 複制到目前Docker建立上下文目錄 static_web 中(因為Dockerfile隻可以操作同一上下文目錄的檔案),
然後在Dockerfile中使用
ADD
指令将 daemon.json 拷貝到目标基礎鏡像的 /etc/docker/daemon.json 目錄下。
修改方法參考連結:https://cr.console.aliyun.com/cn-qingdao/instances/mirrors?accounttraceid=2a028b8d92834921b155ca96c3c5f3e7ytyw
(2)修改Docker DNS
修改
/etc/resolv.conf
檔案内容
# Generated by NetworkManager
search localdomain
nameserver 114.114.114.114
nameserver 8.8.8.8
(3)修改yum源,這些使用了阿裡雲的yum源,從阿裡雲下載下傳yum源配置檔案:
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
将修改好的 CentOS-Base.repo 複制到目前Docker建立上下文目錄 static_web 中(因為Dockerfile隻可以操作同一上下文目錄的檔案),
然後在Dockerfile中使用
ADD
指令将 CentOS-Base.repo 拷貝到目标基礎鏡像的 /etc/yum.repos.d/CentOS-Base.repo 目錄下。
修改方法參考連結:https://developer.aliyun.com/mirror/centos?spm=a2c6h.13651102.0.0.3e221b11BXNk8Q
修改後的Dockerfile如下:
[[email protected] static_web]$ cat Dockerfile
# Version: 0.0.1
FROM centos:7.7.1908
MAINTAINER kanou "[email protected]"
ADD daemon.json /etc/docker/daemon.json
ADD CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo
RUN yum clean all
RUN yum makecache
RUN yum update -y && yum install -y epel-release
RUN yum install -y nginx
#RUN echo 'Hi, I am in your container' > /usr/share/nginx/html/index.html
EXPOSE 80
經過鏡像加速器和yum源修改後,Dockerfile建立Docker鏡像速度快了很多。