2021 new summary: Docker from entry to actual combat, pure dry goods!

Docker introduction

What is Docker?

To be honest about what Docker is, it's not too easy to say, let me explain to you what Docker is in four points.

  • Docker is the world's leading software container platform, which is developed and implemented based on the Go language .
  • Docker can automatically perform repetitive tasks, such as setting up and configuring a development environment, thereby freeing up developers.
  • Users can easily create and use containers, and put their own applications into the container. Containers can also carry out version management, copying, sharing, and modification, just like managing ordinary code.
  • Docker can encapsulate and isolate processes, which is a virtualization technology at the operating system level. Since the isolated process is independent of the host and other isolated processes, it is also called a container.

Official website address: https://www.docker.com/.

What is Docker

Why use Docker?

Docker allows developers to package their applications and dependent packages into a lightweight, portable container, and then publish it to any popular Linux machine, which can also be virtualized.

Containers use the sandbox mechanism completely, and there will be no interfaces between each other (apps similar to iPhone), and more importantly, the container performance overhead is extremely low.

In the traditional development process, our projects usually need to use MySQL, Redis, FastDFS and other environments. These environments need to be downloaded and configured manually. The installation and configuration process is extremely complicated, and the operations under different systems are different. .

The emergence of Docker perfectly solves this problem. We can install software environments such as MySQL and Redis in the container to separate the application and environment architecture. Its advantages are:

  1. Consistent operating environment for easier migration
  2. Encapsulate and isolate the process, the container and the container do not affect each other, and use system resources more efficiently
  3. Multiple consistent containers can be replicated through mirroring

In addition, the open source book "Docker From Getting Started to Practice" has also given the reasons for using Docker.


Docker installation


Next, install Docker. Take the Windows system as an example, visit Docker's official website:


Then click Get Started:


Click here Download for Windowsto download.

If your computer is Windows 10 64位专业版an operating system, you need to turn it Hyper-Von before installing Docker . The way to turn it on is as follows. Open the control panel and select the program:


Click 启用或关闭Windows功能:


Check it Hyper-Vand click OK to:


The computer needs to be restarted after completing the changes.

After opening Hyper-V, we can install Docker. After opening the installer, wait for a while and click Ok:


After the installation is complete, we still need to restart the computer. After restarting, if the following content is prompted:


It means to ask if we use WSL2, which is a Linux subsystem based on Windows. Here we can cancel it, and it will use the Hyper-Vvirtual machine we checked before .

Because it is a graphical interface operation, the specific usage of Docker Desktop is not introduced here.


You can install it directly with Homebrew

brew install --cask docker


Let's take a look at how to install Docker in Linux, here is CentOS7 as an example.

In a test or development environment, Docker officially provides a set of convenient installation scripts in order to simplify the installation process. After executing this script, all preparations will be done automatically and the stable version of Docker will be installed in the system.

curl -fsSL get.docker.com -o get-docker.sh
sh get-docker.sh --mirror Aliyun

After the installation is complete, start the service directly:

systemctl start docker

It is recommended to set self-start after power-on and execute the command:

systemctl enable docker

Several concepts in Docker

Before officially learning Docker, we need to understand several core concepts in Docker:


The image is a read-only template. The image can be used to create Docker containers, and one image can create multiple containers.


A container is a running instance created with an image. Docker uses the container to independently run one or a group of applications. It can be started, started, stopped, and deleted, and each container is an isolated and secure platform. You can think of a container as a simple Linux environment and applications running in it. The definition of the container is almost exactly the same as the mirror image. It is also a unified perspective of a bunch of layers. The only difference is that the top layer of the container is readable and writable.


A warehouse is a place where mirror files are centrally stored. There is a difference between a warehouse and a warehouse registration server. There are often multiple warehouses stored on the warehouse registration server. Each warehouse contains multiple mirrors, and each mirror has a different label. The warehouse is divided into two forms: public warehouse and private warehouse. The largest public warehouse is DockerHub, which stores a large number of images for users to download. Domestic public warehouses include Alibaba Cloud, NetEase Cloud, etc.

to sum up

In layman's terms, an image represents a piece of software; and running based on a certain image is to generate a program instance, which is a container; and the warehouse is used to store all the images in Docker.

The warehouse is divided into remote warehouse and local warehouse. Similar to Maven, if you download dependencies from remote every time, efficiency will be greatly reduced. For this reason, Maven’s strategy is to download dependencies to the local warehouse when they are accessed for the first time. For the second and third use, you can directly use the dependency of the local warehouse. Docker's remote warehouse and local warehouse have similar functions.

Docker first experience

Let's make a preliminary use of Docker. Here is an example of downloading a MySQL image (在CentOS7下进行).

Like GitHub, Docker also provides a DockerHub for querying the addresses of various mirrors and installation tutorials. For this, we first visit DockerHub: https://hub.docker.com/


Type in the search box in the upper left corner MySQLand press Enter:


You can see that there are many mirrors related to MySQL. If there is a OFFICIAL IMAGElogo in the upper right corner , it means it is an official mirror, so we click on the first MySQL mirror:


The instruction to download the MySQL image is provided on the right docker pull MySQL, but this instruction will always download the latest version of the MySQL image.

If you want to download the specified version of the mirror, click the following View Available Tags:


You can see the images of various versions here, and there are download instructions on the right, so if you want to download the MySQL image of version 5.7.32, execute:

docker pull MySQL:5.7.32

However, the process of downloading the image is very slow, so we need to configure the image source to speed up the download, visit the 阿里云official website:


Click on the console:


Then click the menu in the upper left corner, hover the mouse over products and services in the pop-up window, and search for container mirroring services on the right, and finally click on container mirroring services:


Click on the mirror accelerator on the left and execute the configuration instructions on the right one by one.

sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
  "registry-mirrors": ["https://679xpnpz.mirror.aliyuncs.com"]
sudo systemctl daemon-reload
sudo systemctl restart docker

Docker mirroring instructions

Docker needs to frequently operate related mirrors, so let's first understand the mirroring instructions in Docker.

To see which mirror Docker currently have, you can use the docker imagescommand.

[[email protected] ~]# docker images
MySQL         5.7.32    f07dfa83b528   11 days ago     448MB
tomcat        latest    feba8d001e3f   2 weeks ago     649MB
nginx         latest    ae2feff98a0c   2 weeks ago     133MB
hello-world   latest    bf756fb1ae65   12 months ago   13.3kB

Among them REPOSITORYis the image name, TAGthe version mark, IMAGE IDthe image id (unique), and CREATEDthe creation time. Note that this time is not the time when we downloaded the image to Docker, but the time when the image creator created it, which SIZEis the image size.

This command can query the specified image name:

docker image MySQL

If you do this, all MySQL images in Docker will be queried:

[[email protected] ~]# docker images MySQL
MySQL        5.6       0ebb5600241d   11 days ago     302MB
MySQL        5.7.32    f07dfa83b528   11 days ago     448MB
MySQL        5.5       d404d78aa797   20 months ago   205MB

This command can also carry the -pparameter:, docker images -qwhich -qmeans that only the id of the image is displayed:

[[email protected] ~]# docker images -q

If you want to download the mirror, use:

docker pull MySQL:5.7

docker pullIt is fixed, write the name of the image to be downloaded and the version flag at the back; if you do not write the version flag but execute it directly docker pull MySQL, the latest version of the image will be downloaded.

Generally, before downloading the mirror, we need to search for the version of the mirror to download the specified version. Use the command:

docker search MySQL

However, this command can only view the mirror information related to MySQL, but not which version is available. If you want to know the version, you can only query like this:

docker search MySQL:5.5

If the queried version does not exist, the result is empty:


Delete mirror usage instructions:

docker image rm MySQL:5.5

If the version is not specified, the latest version will be deleted by default.

You can also delete by specifying the mirror id:

docker image rm bf756fb1ae65

However, an error was reported at this time:

[[email protected] ~]# docker image rm bf756fb1ae65
Error response from daemon: conflict: unable to delete bf756fb1ae65 (must be forced) - image is being used by stopped container d5b6c177c151

This is because the hello-worldimage to be deleted is running, so the image cannot be deleted. At this time, the deletion needs to be executed forcibly:

docker image rm -f bf756fb1ae65

This instruction will delete all the image and the container executed by the image, use it with caution.

Docker also offers a simplified version to remove the mirror: docker rmi 镜像名:版本标志.

At this point, we can use rmiand -pperform some joint operations. For example, if you want to delete all MySQL mirrors now, you need to query the id of the MySQL mirror and docker rmidelete them one by one according to these id . But now, we can do this:

docker rmi -f $(docker images MySQL -q)

First, by docker images MySQL -qquerying all the mirror ids of MySQL, it -qmeans that only the ids are queried, and these ids are passed to the docker rmi -fcommand as parameters , so that all the MySQL mirrors are deleted.

Docker container instructions

After mastering the relevant instructions for mirroring, we need to understand the instructions for the container, which is based on mirroring.

If you need to run a container through mirroring, use:

docker run tomcat:8.0-jre8

Of course, the premise of running is that you have this mirror, so download the mirror first:

docker pull tomcat:8.0-jre8

After the download is complete, you can run, run check containers currently running: docker ps.


Among them CONTAINER_IDis the id of the container, IMAGEthe name of the image, COMMANDthe command executed in the CREATEDcontainer, the creation time STATUSof the container, the state PORTSof the container, the listening port of the service in the NAMEScontainer, and the name of the container.

The tomcat running in this way cannot be directly accessed from the outside, because the container has isolation. If you want to directly access the tomcat inside the container through port 8080, you need to map the host port and the port in the container:

docker run -p 8080:8080 tomcat:8.0-jre8

Explain the role of these two ports ( 8080:8080), the first 8080 is the host port, the second 8080 is the port in the container, and external access to port 8080 will access the port 8080 in the container through mapping.

Tomcat can be accessed externally at this time:


If it is mapped like this:

docker run -p 8088:8080 tomcat:8.0-jre8

Then you need to access port 8088 to access tomcat. It should be noted that the containers that are run each time are independent of each other, so running multiple tomcat containers at the same time will not cause port conflicts.

The container can also run in the background so that it does not occupy the terminal:

docker run -d -p 8080:8080 tomcat:8.0-jre8

When starting the container, the container will be given a name by default, but this name can actually be set. Use the command:

docker run -d -p 8080:8080 --name tomcat01 tomcat:8.0-jre8

The container name at this time is tomcat01, and the container name must be unique.

Let's extend docker psa few of the command parameters, such as -a:

docker ps -a

This parameter will list all running and non-running containers:


-qThe only parameter queries vessel id running: docker ps -q.

[[email protected] ~]# docker ps -q

If used in combination, the query id all containers of operational and non-operational: docker ps -qa.

[[email protected] ~]# docker ps -aq

The next is the stop and restart instructions of the container, because it is very simple, it will not be introduced too much.

docker start c2f5d78c5d1a

Through this instruction, the container that has been stopped can be run, and it can be started by the id of the container or by the name of the container.

docker restart c2f5d78c5d1a

This command can restart the specified container.

docker stop c2f5d78c5d1a

This command can stop the specified container.

docker kill c2f5d78c5d1a

This command can directly kill the specified container.

The above instructions can be used in conjunction with the container id and container name.

When the container is stopped, although the container is no longer running, it still exists. If you want to delete it, use the command:

docker rm d5b6c177c151

It should be noted that the id of the container does not need to be written out all, only a unique identification is required.

If you want to delete a running container, you need to add a -fparameter to force deletion:

docker rm -f d5b6c177c151

If you want to delete all containers, you can use the combined command:

docker rm -f $(docker ps -qa)

First docker ps -qaquery the ids of all containers, and then docker rm -fdelete them.

When the container is running in the background, we cannot know the running status of the container. If you need to view the running log of the container at this time, use the command:

docker logs 289cc00dc5ed

The log displayed in this way is not real-time. If you want to display it in real-time, you need to use -fparameters:

docker logs -f 289cc00dc5ed

-tThe time stamp of the log can also be displayed through parameters, which are usually used in conjunction with -fparameters:

docker logs -ft 289cc00dc5ed

To view which processes are running in the container, you can use the command:

docker top 289cc00dc5ed

If you want to interact with the container, use the command:

docker exec -it 289cc00dc5ed bash

At this time, the terminal will enter the container, and the executed instructions will take effect in the container. Only some simple instructions can be executed in the container, such as ls, cd, etc. If you want to exit the container terminal, return to CentOS. Just execute it exit.

Now that we have been able to enter the container terminal to perform related operations, how do we deploy a project to the tomcat container?

docker cp ./test.html 289cc00dc5ed:/usr/local/tomcat/webapps

docker cpThe file can be copied from CentOS to the container through instructions, which ./test.htmlis the resource path in CentOS, the 289cc00dc5edcontainer id, and /usr/local/tomcat/webappsthe resource path of the container. At this time, the test.htmlfile will be copied to the path.

[[email protected] ~]# docker exec -it 289cc00dc5ed bash
[email protected]:/usr/local/tomcat# cd webapps
[email protected]:/usr/local/tomcat/webapps# ls
[email protected]:/usr/local/tomcat/webapps#

If you want to copy the files in the container to CentOS, you can write in reverse:

docker cp 289cc00dc5ed:/usr/local/tomcat/webapps/test.html ./

So now if you want to deploy the project, upload the project to CentOS first, then copy the project from CentOS to the container, and then start the container.

Although it is very simple to use Docker to start the software environment, it also faces a problem. We cannot know the specific details inside the container, such as the listening port, bound ip address, etc. Fortunately, these Docker have helped us think about it. Need to use instructions:

docker inspect 923c969b0d91

Docker data volume

After learning the relevant instructions of the container, let's take a look at the data volume in Docker. It can realize file sharing between the host and the container. Its advantage is that the modification of the host's files will directly affect the container without Then copy the files of the host computer to the container.

Now if you want to make a data volume /opt/appsbetween the webappsdirectory in the host machine and the directory in the container , you should write the command like this:

docker run -d -p 8080:8080 --name tomcat01 -v /opt/apps:/usr/local/tomcat/webapps tomcat:8.0-jre8

However, if you visit tomcat at this time, you will find that you cannot access:


This means that our data volume setting is successful. Docker will synchronize the webappsdirectory in the container with the directory /opt/apps. At this time, the /opt/appsdirectory is empty, causing the webappsdirectory to become an empty directory, so it cannot be accessed.

At this point, we only need to /opt/appsadd files to the directory, which will make the webappsdirectory have the same files and achieve file sharing. Test it:

[[email protected] opt]# cd apps/
[[email protected] apps]# vim test.html
[[email protected] apps]# ls
[[email protected] apps]# cat test.html
<h1>This is a test html!</h1>

In /opt/appscreating a directory test.htmlfile, then in the container webappsif the directory of the file will do? Enter the terminal of the container:

[[email protected] apps]# docker exec -it tomcat01 bash
[email protected]:/usr/local/tomcat# cd webapps/
[email protected]:/usr/local/tomcat/webapps# ls

The file does already exist in the container, so let's write a simple Web application:

public class HelloServlet extends HttpServlet {

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().println("Hello World!");

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

This is a very simple Servlet, we package it and upload /opt/appsit to the file, then the container will definitely be synchronized to the file, and access at this time:


The data volume set in this way is called a custom data volume, because the directory of the data volume is set by ourselves, and Docker also provides us with another way to set the data volume:

docker run -d -p 8080:8080 --name tomcat01 -v aa:/usr/local/tomcat/webapps tomcat:8.0-jre8

At this time, it is aanot the directory of the data volume, but the alias of the data volume. Docker will automatically create a aadata volume for us , and webappscopy all the contents of the directory in the container to the data volume. The location is in the /var/lib/docker/volumesdirectory:

[[email protected] volumes]# pwd
[[email protected] volumes]# cd aa/
[[email protected] aa]# ls
[[email protected] aa]# cd _data/
[[email protected] _data]# ls
docs  examples  host-manager  manager  ROOT

At this point, we only need to modify the contents of the directory to be able to affect the container.

Finally, I will introduce a few container and mirror-related instructions:

docker commit -m "描述信息" -a "镜像作者" tomcat01 my_tomcat:1.0

This command can package the container into a mirror, and query the mirror at this time:

[[email protected] _data]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
my_tomcat           1.0                 79ab047fade5        2 seconds ago       463MB
tomcat              8                   a041be4a5ba5        2 weeks ago         533MB
MySQL               latest              db2b37ec6181        2 months ago        545MB

If you want to back up the image, you can use the command:

docker save my_tomcat:1.0 -o my-tomcat-1.0.tar
[[email protected] ~]# docker save my_tomcat:1.0 -o my-tomcat-1.0.tar
[[email protected] ~]# ls
anaconda-ks.cfg  initial-setup-ks.cfg  公共  视频  文档  音乐
get-docker.sh    my-tomcat-1.0.tar     模板  图片  下载  桌面

If you have a .tarformat image, how do you load it into Docker? Execution instructions:

docker load -i my-tomcat-1.0.tar
[email protected] ~]# docker load -i my-tomcat-1.0.tar
b28ef0b6fef8: Loading layer [==================================================>]  105.5MB/105.5MB
0b703c74a09c: Loading layer [==================================================>]  23.99MB/23.99MB
Loaded image: my_tomcat:1.0
[[email protected] ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
my_tomcat           1.0                 79ab047fade5        7 minutes ago       463MB

At last:

I recently compiled a complete set of **"Summary of JAVA Core Knowledge Points"**. To be honest, as a Java programmer, whether you need an interview or not, you should take a good look at this information. There is always no loss when you get it~ Many of my fans also get offers from companies such as Tencent Byte Kuaishou.

Enter the [ Java Architecture Resource Exchange Group ] and ask the administrator to get it -!