Utilize the Squash function (experimental function added after 1.13)
1. Before starting the Docker Daemon process, set the experimental parameter to true;
the docker v20 version is /etc/docker/daemon.json
enabled by modifying:
{
"experimental": true
}
2. There is no difference between the written dockerfile and the previous one.
3. When compiling, add --squash
parameters.
docker build --squash -t xxx:xxx .
The squash function compresses the size of the image on the one hand, and saves the image construction information on the other. However, this method is experimental and needs to be used with caution.
Use a smaller base image
- System images use Ubuntu, CentOs, Alpine, scratch, buybox, etc.
- Many official website images provide slim versions.
The disadvantage of the above method is that due to the small size of the basic image, it may lack the dependencies or tools we need, which needs to be gradually supplemented, which consumes a large amount of work.
Dockerfile instruction optimization
Instruction splicing
When defining a Dockerfile, using RUN
instructions multiple times will generate multiple image layers, making the image bloated. Multiple instructions should be concatenated into one RUN
( implemented by the operator sum) &&
./
Instruction optimization
If executed in the RUN command apt
, you can use the configuration options apk
of yum
the command itself to reduce the number of image layers and image size.
apt-get install -y
By adding options during execution--no-install-recommends
, you do not need to install recommended (non-required) dependencies, or you canapk add
add options during execution--no-cache
to achieve the same effect;- During execution
yum install -y
, multiple tools are installed at the same time, such asyum install -y gcc gcc-c++ make
; - The installation and cleaning of components should be connected in series in one instruction, such as
apt-get install zip && rm -rf /var/cache/apk/*
Use the export and import instructions
# 启动一个容器
docker run -d --name test test:2.0
# 利用export和import将容器导出变为镜像
docker export test | docker import - test:3.0
This method can also effectively reduce the image size, but will lose the image build information.