Docker container: three methods of creating docker images and dockerfile cases

Table of contents

1. Create based on an existing image

1. Create a boot image

2. Generate a new image

2. Create based on local templates 

1. OPENVZ download template

2. Import container to generate image

3. Create based on dockerfile 

1. Dockerfile structure and layering

2. Joint file system

3. The principle of docker image loading

4. Commonly used instructions for dockerfile operations

(1) FROM instruction

(2) MAINTAINER instruction

(3) RUN instruction

(4) ENTRYPOINT command

(5) CMD command

(6) EXPOSE command

(7) ENV command

(8) ADD instruction

(9) COPY command

(10) VOLUME instruction

(11) USER command

(12) WORKDIR command

(13) ONBUILD command

(14)HEALTHCHECK

4. Dockerfile builds a mirror instance

1. Dockerfile builds an httpd instance

2. Dockerfile builds sshd instance

3. dockerfile build systemd instance

4. Dockerfile builds nginx instance


1. Create based on an existing image

1. Create a boot image

(1)首先启动一个镜像,在容器里做修改
docker run -itd centos:7 /bin/bash
#创建并启动镜像
docker ps 
#查看启动的镜像信息

2. Generate a new image

(2)将修改后的容器提交为新的镜像,需要使用该容器的 ID 号创建新镜像
docker commit -m "new-images" -a  "test" dda50e36fd55   centos:test
#常用选项:
-m 说明信息;
-a 作者信息;
-p 生成过程中停止容器的运行;

docker images
#查看新生成的镜像

2. Create based on local templates 

1. OPENVZ download template

通过导入操作系统模板文件可以生成镜像,模板可以从 OPENVZ 开源项目下载,下载地址为http://openvz.org/Download/template/precreated

wget http://download.openvz.org/template/precreated/debian-7.0-x86-minimal.tar.gz

2. Import container to generate image

cat debian-7.0-x86-minimal.tar.gz | docker import - debian:test
#查看这个模板导入到docker的debian:test镜像

3. Create based on dockerfile 

1. Dockerfile structure and layering

①The dockerfile structure is roughly divided into four parts: basic image information, maintainer information, image operation instructions, and execution instructions when the container starts

Dockerfile is a text file, which contains a series of instructions (Instruction), each instruction builds a layer, so the content of each instruction is to describe how the layer should be built. With Dockerfile, when we need to customize our own additional requirements, we only need to add or modify instructions on the Dockerfile and regenerate the image, saving the trouble of typing commands.

In addition to manually generating Docker images, you can use Dockerfile to automatically generate images. Dockerfile is a file composed of multiple instructions, each of which corresponds to a command in Linux, and the Docker program will read the instructions in the Dockerfile to generate a specified image

②Structural layering of docker image:

(1) Each instruction in the Dockerfile will create a new image layer;

(2) The image layer will be cached and reused;

(3) When the instructions of the Dockerfile are modified, the copied file changes, or the variables specified when building the image are different, the corresponding image layer cache will become invalid;

(4) If the image cache of a certain layer is invalid, the cache of the image layer after it will be invalid;

(5) The image layer is immutable. If you add a file in one layer and then delete it in the next layer, the file will still be included in the image, but the file will not be affected if it is invisible in the container. data in the mirror.

2. Joint file system

Union File System (unionFS): A layered, lightweight and high-performance file system, that is, a layer-by-layer superposition and then made into a mirror image. The bottom layer is loaded by the kernel, then the rootfs system, and the upper layer is the read-only basis Image, after the image is started, it becomes a container, which is a readable and writable layer. This layer stores data, etc., and then can be packaged into a new image to store data.

Features: Load multiple file systems at the same time, but from the outside, only one file system can be seen. Joint loading will superimpose the file systems of all layers, so that the final file system will contain all underlying files and directories.

The layers we see when we download are the joint file system.

3. The principle of docker image loading

①Docker's image is actually composed of layer-by-layer file systems, and this layer of file systems is UnionFS

②bootfs mainly includes bootloader and kernel. The bootloader is mainly used to guide and load the kernel. When Linux starts, it will load the bootfs file system.

③The bottom layer of the Docker image is bootfs, which is the same as our typical Linux/Unix system, including the boot loader and kernel. When the boot loading is complete, the entire kernel is in the memory. At this time, the right to use the memory has been transferred from the bootfs to the kernel. At this time, the system will also unload the bootfs.

④ We can understand that there is nothing in the kernel at the beginning, and a command is used to download debian, and then a layer of basic image will be added to the kernel; after installing emacs, a layer of image will be superimposed on the basic image; and then install An apache will superimpose another layer of image on top of images. In the end they look like a filesystem i.e. the rootfs of the container. In the Docker system, these rootfs are called Docker images. However, at this time, each layer of rootfs is read-only, and we cannot operate it at this time. When we create a container, that is, instantiate the Docker image, the system will allocate an empty read-write rootfs on top of one or more layers of read-only rootfs.

⑤Why the size of centos in the container is only 200M

Because for a streamlined OS, the rootfs can be very small, and only needs to contain the most basic commands, tools, and program libraries. Because the underlying layer directly uses the kernel of the host machine, you only need to provide the rootfs. It can be seen that for different Linux distributions, the bootfs is basically the same, and the rootfs will be different, so different distributions can share the bootfs.

4. Commonly used instructions for dockerfile operations

(1) FROM instruction

It is used to specify the basic entry on which to generate a new image. The first command of the dockerfile must be FROM to specify the base image process on which the image is generated this time. A FROM is required for each image created.

(2) MAINTAINER instruction

Indicates the maintainer information for the new image

(3) RUN instruction

Execute commands on the based mirror and submit to the new mirror, such as performing yum installation, etc.

(4) ENTRYPOINT command

ENTRYPOINT ["program to run", "parameter 1", "parameter 2"]

Set the command and its parameters to be run first when the container is started. This command is the command parameter added when entering the container with docker exec.
You can override the content of the ENTRYPOINT directive in the image by using the command docker run --entrypoint

(5) CMD command

CMD ["program to run", "parameter 1", "parameter 2"]

This instruction is the first command or step after entering the container, and the first command executed in the shell in the container after entering the container. There can only be one CMD command in the dockerfile. If there are multiple CMDs, only the last command will be executed. .

If a command is specified during docker run or there is an ENTRYPOINT command in the image, the CMD program will not be executed.

docker RUN priority > ENTRYPOINT command > CMD command

(6) EXPOSE command

EXPOSE "port number"

Specify the port to be opened when the new image generated by the dockerfile is loaded into Docker

(7) ENV command

ENV environment variable variable value

(8) ADD instruction

ADD source path target path

The ADD command is used to copy the source file to the new image generated by the dockerfile, and the source file must be in the same folder as the dockerfile, or under the same url. There are the following considerations:

①When the source path is a file and the target path ends with /, dockerfile will treat the target file as a directory and save the file in the source path to the directory of the template path, and automatically create the template path if the template path does not exist

②When the source path is a file and the target path does not end with /, dockerfile will treat the target path as a file, and directly overwrite the content of the target path file but the name will not change. If the template path does not exist, it will create a target path named The file, the content is the file content of the source path

③When the source path is a folder, if the target path exists, directly copy the folder of the original path to the directory of the template path.

If the target path does not exist, a folder named after the target path will be automatically created and the source folder will be copied to the directory.

④If the source file is an archive file or a compressed file, docker will automatically help decompress it. The URL download and decompression features cannot be used together. Any compressed files copied by URL will not be automatically decompressed.

(9) COPY command

copy source file/directory target file/directory

Only copy files/directories on the local host. The copy target point is in the mirror. It is required that the local file must be in the same path as the dockerfile.

Comparison between ADD and copy:

① All have the function of copying files and directories locally to the mirror

②ADD copy archive files and compressed files will be automatically decompressed

③All require to be in the same folder as the dockerfile

④URL pull directory to copy

⑤COPY can only copy the local host file to the mirror, ADD can copy to the url

(10) VOLUME instruction

volume ["directory"]

Create a mount point in the container

(11) USER command

USER username/uid

Specify the user when running the container

(12) WORKDIR command

Specifying the working directory for the subsequent RUN/CMD/ENTRYPOINT can be understood as switching to the specified directory to execute other commands such as RUN.

(13) ONBUILD command

Specify the commands to be allowed when the generated image is used as a base image. When calling the image with the ONBUILD command, the ONBUILD command will be executed first. When using other mirrors, carefully check the contents of the ONBUILD command.

When the ONBUILD instruction is added to a Dockerfile, the instruction will not have any substantial impact on using the Dockerfile to build an image (such as an A image). But when writing a new Dockerfile to build a mirror based on the A mirror (such as a B mirror), the ONBUILD command in the Dockerfile that constructs the A mirror will take effect at this time. In the process of building the B mirror, it will first execute The instructions specified by the ONBUILD instruction are executed before other instructions are executed.

(14)HEALTHCHECK

health examination

4. Dockerfile builds a mirror instance

1. Dockerfile builds an httpd instance

mkdir  /opt/apache
cd     /opt/apache
#创建并进入文件夹,每个服务一个文件夹
vim Dockerfile
#创建Dockerfile文件,文件内容如下
FROM  centos:7
#基于的基础镜像指定为centos:7,注意本机要有此基础镜像
MAINTAINER this  is  apache  image  <test>
#说明镜像维护人信息为,指定用户为test
RUN yum -y update
RUN yum -y install httpd 
#镜像RUN指令指定启动容器后的运行命令,yum安装update和httpd服务
EXPOSE 80
#开启80端口
ADD index.html  /var/www/html/index.html
#复制宿主机index.html文件到容器的 /var/www/html/index.html
ENTRYPOINT ["/usr/sbin/apachectl"]
CMD ["-D","FOREGROUND"]
#使用前台启动apache注意使用绝对路径,如果后台启动,启动完shell就结束了容器就结束了,保存退出。
echo "this is  test web">index.thml
#准备网站的网页,注意必须在和Dockerfile文件相同的目录
docker build -t  httpd:centos .  
#将dockerfile 文件生成镜像注意最后有个点。
docker run -d -p 40330:80  httpd:centos 
#新镜像运行容器,映射宿主机的40330端口为容器的80端口
访问192.168.30.11:40330 进行测试是否可以访问容器的httpd主业

2. Dockerfile builds sshd instance

FROM centos:7
#指定sshd基于centos:7的镜像
MAINTAINER this is ssh image <ssh>
#说明镜像信息,镜像用户为ssh
RUN yum -y update
#此内容若保存可注释掉
#运行RUN指令执行update更新
RUN yum -y install openssh* net-tools lsof telnet passwd
#RUN指令执行安装openssh相关工具,net工具,lsof、telnet、passwd程序
RUN echo "abc123" |passwd --stdin root
#免交互设置root密码为abc123
RUN sed -i 's/UsePAM yes/UsePAM no/g' /etc/ssh/sshd_config
#关闭sshd服务的pam认证
RUN sed -i '12d' /etc/pam.d/sshd
#删除/etc/pam.d/sshd的12行,删除12行为取消pam的限制
RUN ssh-keygen -t rsa -A
#生成秘钥认证文件
RUN mkdir -p /root/.ssh && chown root.root /root && chmod 700 /root/.ssh
#递归创建/root/.ssh文件夹并修改属主属租为root,添加权限为700只允许属组属组用户操作
EXPOSE 22
#规定端口为22
ENTRYPOINT [ "/usr/sbin/sshd" ]
CMD ["-D", "FOREGROUND"]
#/usr/sbin/sshd -D用于前台启动sshd服务
docker  build -t  sshd:centos .
#创建sshd;centos镜像
docker run -d -p 40022:22 sshd:centos
#运行sshd:centos容器并映射容器中的22端口为40022端口
docker ps 
#查看容器信息
ssh localhost   -p   40022
ifconfig
#宿主机执行验证sshd容器

 

3. dockerfile build systemd instance

mkdir /opt/systemctl
cd /opt/systemctl
#创建systemd目录
vim Dockerfile
#编辑Dockerfile文件内容如下
FROM sshd:centos
#以sshd:centos为基础镜像,注意要做上面的sshd实例,不然无此进项不能制作systemd镜像
MAINTAINER this is systemctl image <systemd>
ENV container docker
#除了systemd-tmpfiles-setup.service,删除其它所有文件
RUN (cd /lib/systemd/system/sysinit.target.wants/; for i in *; do [ $i == systemd-tmpfiles-setup.service ] || rm -f $i;done); \
rm -f /lib/systemd/system/multi-user.target.wants/*; \
rm -f /etc/systemd/system/*.wants/*; \
rm -f /lib/systemd/system/local-fs.target.wants/*; \
rm -f /lib/systemd/system/sockets.target. wants/*udev*; \
rm -f /lib/systemd/system/sockets.target.wants/*initctl*; \
rm -f /lib/systemd/system/basic.target.wants/*;\
rm -f /lib/systemd/system/anaconda.target.wants/*;
VOLUME [ "/sys/fs/cgroup" ]
CMD ["/usr/sbin/init"]
docker build -t systemd:centos .
#生成systemd镜像
docker run --privileged -d -P -v /sys/fs/cgroup:/sys/fs/cgroup:ro systemd:centos /sbin/init
#启动容器,并挂载宿主机目录挂载到容器中,和进行初始化
#--privileged:使container内的root拥有真正的root权限。否则,container内的root只是外部的一个普通用户权限。
docker ps -a
docker exec -it 56b06afcef9a  /bin/bash
#进入容器
systemctl start sshd
systemctl status sshd

 

4. Dockerfile builds nginx instance

mkdir /opt/nginx
cd /opt/nginx/
cp /opt/nginx-1.12.0.tar.gz /opt/nginx
#创建nginx目录,将nginx安装包放到创建的nginx目录下,必须与Dockerfile文件在同一目录下
vim Dockerfile
#编辑nginx的dockerfile文件内容如下
FROM centos:7
#基于基础镜像,centos
MAINTAINER this is nginx image <nginx>
#用户信息,镜像维护用户为nginx
RUN yum -y update
#此内容若保存可注释掉
RUN yum -y install pcre-devel zlib-devel gcc gcc-C++ make
RUN useradd -M -s /sbin/ nologin nginx
#安装编译安装工具
ADD nginx-1.12.0.tar.gz /opt/
#上传nginx软件压缩包,docker自动解压
WORKDIR /opt/nginx-1.12.0
RUN ./ configure \
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-http_stub_status_module && make && make install
ENV PATH /usr/local/nginx/sbin:$PATH
#指定工作目录
EXPOSE 80
EXPOSE 443
#指定http和https端口
RUN echo "daemon off;" >> /usr/local/nginx/conf/nginx.conf    
#关闭nginx 在后台运行
ADD run.sh /run.sh
RUN chmod 755 /run.sh
CMD ["/run.sh"]
#添加宿主机中run.sh到容器中
vim run.sh
#创建run.sh脚本,注意必须和dockerfile在同一路径下,内容如下
#!/bin/bash
/usr/local/nginx/sbin/nginx
docker build -t nginx:centos .
docker run -itd -P nginx:centos /bin/bash
docker ps -a 
#查看nginx容器,访问80对应的随机端口验证,443的端口验证不了,ngingx中每家ssl模块
http://192.168.30.11:32769

5. Solve the problem of network error when creating an instance

报错:[Warning] IPv4 forwarding is disabled. Networking will not work. 

Solution:
vim /etc/sysctl.conf
net.ipv4.ip_forward=1

sysctl -p
systemctl restart network
systemctl restart docker

Guess you like

Origin blog.csdn.net/weixin_67287151/article/details/130264947