How to create a centos7 docker base image

来自koorka知识分享
跳转至: 导航搜索

This article covers how to build a CentOS 7.3 docker image from scratch and use it in docker. In order to build this image you either should have access to CentOS repository or have DVD to install the base system from. I’ll be installing it from a DVD.

We’ll be using yum and rpm to initialize the image’s root directory.

Initialize the RPM database

Initialize the RPM database so that we can install all of the software we need in the image: we will need to create the directory for the database because RPM expects it to exist, and then use the RPM “rebuilddb” command:
centos7_root=/opt/chroot/centos7
mkdir -p ${centos7_root}/var/lib/rpm
rpm --root $centos7_root --initdb
In order for YUM to manage and install software into our image it needs to know which CentOS version to install – for this the package centos-release to be installed in the image.
mkdir -p /media/cdrom
mount -o loop CentOS-7-x86_64-Minimal-1611.iso /media/cdrom
rpm --root ${centos7_root} -ivh /media/cdrom/Packages/centos-release*
make sure the YUM repository:
cat ${centos7_root}/etc/yum.repos.d/CentOS-Media.repo

Install yum and rpm in the image

yum -y --installroot=${centos7_root} install yum rpm
At this point you have a small environment which you can chroot into and modify it the way you like
chroot ${centos7_root} /bin/bash
You will drop to a bash shell in the newly created system, I won’t do any further changes to this system except modifying the banner
echo 'CentOS 7.3 Docker image' > /etc/motd
exit
Change the timezone to you want:
cd /etc
rm localtime 
ln -s ../usr/share/zoneinfo/Asia/Shanghai localtime

Remove the files that's  unnecessary to  decrease the image size

  • only support english and chinese language:
chroot ${centos7_root} /bin/bash
localedef --list-archive |egrep -v ^"en|zh" |xargs localedef --delete-from-archive
mv -f /usr/lib/locale/locale-archive /usr/lib/locale/locale-archive.tmpl
build-locale-archive
Clean yum cache:
yum clean all
Remove all language exclude english and chinese:
cd /usr/share/locale
ls |egrep -v ^"en|zh" |xargs rm -rf
Remove docs and manuals:
rm -rf /usr/share/doc
rm -rf /usr/share/man

Import Docker Image

cd /opt/chroot
 tar -C centos7/ -c . | docker import - koorka/centos:7.3
If the import goes well, you will see the ID of the newly imported image.
docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
koorka/centos       7.3                 e51a570c3487        9 minutes ago       333.3 MB
And start the new image:
docker run --rm --name=centos7 koorka/centos:7.3 cat /etc/motd
Or enter the container interactive mode:
docker run -it --name=centos7 koorka/centos:7.3 /bin/bash