前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >最简单的Docker镜像教程:从头基于空镜像scratch创建一个新的Docker镜像

最简单的Docker镜像教程:从头基于空镜像scratch创建一个新的Docker镜像

原创
作者头像
Jerry Wang
修改2021-08-06 10:06:01
13K0
修改2021-08-06 10:06:01
举报

我们在使用Dockerfile构建docker镜像时,一种方式是使用官方预先配置好的容器镜像。优点是我们不用从头开始构建,节省了很多工作量,但付出的代价是需要下载很大的镜像包。

比如我机器上docker images返回的这些基于nginx的镜像,每个都超过了100MB,而一个简单的Ubuntu的容器超过了200MB,如果安装了相关的软件,尺寸会更大。

如果我们的需求是在构建一个符合我们实际业务需求的Docker镜像的前提下,确保镜像尺寸尽可能的小,应该怎么做呢?

思路是使用空镜像scratch。

新建一个文件夹,用wget下载rootfs.tar.xz压缩包。

代码语言:txt
复制
wget -O rootfs.tar.xz https://github.com/debuerreotype/docker-debian-artifacts/raw/b024a792c752a5c6ccc422152ab0fd7197ae8860/jessie/rootfs.tar.xz

这个将近30MB的压缩包是个什么东东?

解压之后看内容就知道了,包含了操作系统大部分常用命令。

代码语言:txt
复制
wget -O nginx.conf https://github.diablo.corp/raw/slvi/docker-k8s-training/master/docker/res/nginx.conf

新建一个dockerfile文件,将下列内容粘贴进去:

代码语言:txt
复制
FROM scratch

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

# 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.diablo.corp/raw/slvi/docker-k8s-training/master/docker/res/cheers.jpg && \
wget --no-check-certificate -O /usr/share/nginx/html/index.html https://github.diablo.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;"]

执行命令进行镜像的构建:

代码语言:txt
复制
docker build -t nginx-from-scratch1.0 .

产生的日志:

最后看到镜像成功构建的消息。

基于这个名为nginx-from-scratch的镜像启动一个新的nginx容器:

localhost:1083, 看到首页,说明这个新构建的镜像工作正常。

要获取更多Jerry的原创文章,请关注公众号"汪子熙":

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档