從頭基於空鏡像scratch創建一個新的Docker鏡像 原

我們在使用Dockerfile構建docker鏡像時,一種方式是使用官方預先配置好的容器鏡像。優點是我們不用從頭開始構建,節省了很多工作量,但付出的代價是需要下載很大的鏡像包。

比如我機器上docker images返回的這些基於nginx的鏡像,每個都超過了100MB,而一個簡單的Ubuntu的容器超過了200MB,如果安裝了相關的軟件,尺寸會更大。

如果我們的需求是在構建一個符合我們實際業務需求的Docker鏡像的前提下,確保鏡像尺寸儘可能的小,應該怎麼做呢?

思路是使用空鏡像scratch。

新建一個文件夾,用wget下載rootfs.tar.xz壓縮包。

wget -O rootfs.tar.xz https://github.com/debuerreotype/docker-debian-artifacts/raw/b024a792c752a5c6ccc422152ab0fd7197ae8860/jessie/rootfs.tar.xz

這個將近30MB的壓縮包是個什麼東東?

解壓之後看內容就知道了,包含了操作系統大部分常用命令。

wget -O nginx.conf https://github.wdf.sap.corp/raw/slvi/docker-k8s-training/master/docker/res/nginx.conf

新建一個dockerfile文件,將下列內容粘貼進去:

FROM scratch

# set the environment to honour SAP's proxy servers
ENV http_proxy http://sap.corp:8080
ENV https_proxy http://sap.corp:8080
ENV no_proxy .sap.corp

# give yourself some credit
LABEL maintainer="Jerry Wang"

# add and unpack an archive that contains a Debian root filesystem
ADD rootfs.tar.xz /

# use the apt-get package manager to install nginx and wget
RUN apt-get update && \
apt-get -y install nginx wget

# use wget to download a custom website into the image
RUN wget --no-check-certificate -O /usr/share/nginx/html/cheers.jpg https://github.wdf.sap.corp/raw/slvi/docker-k8s-training/master/docker/res/cheers.jpg && \
wget --no-check-certificate -O /usr/share/nginx/html/index.html https://github.wdf.sap.corp/raw/slvi/docker-k8s-training/master/docker/res/cheers.html

# copy the custom nginx configuration into the image
COPY nginx.conf /etc/nginx/nginx.conf

# link nginx log files to Docker log collection facility
RUN ln -sf /dev/stdout /var/log/nginx/access.log && \
ln -sf /dev/stderr /var/log/nginx/error.log

# expose port 80 - the standard port for webservers
EXPOSE 80

# and make sure that nginx runs when a container is created
CMD ["nginx", "-g", "daemon off;"]

執行命令進行鏡像的構建:

docker build -t nginx-from-scratch1.0 .

產生的日誌:

最後看到鏡像成功構建的消息。

基於這個名爲nginx-from-scratch的鏡像啓動一個新的nginx容器:

localhost:1083, 看到首頁,說明這個新構建的鏡像工作正常。 要獲取更多Jerry的原創文章,請關注公衆號"汪子熙":

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章