I. Introduction to Docker

Docker is an operating system-level virtualization technology, which is a lightweight container engine built on LXC technology.

LXC technology: LXC stands for Linux Container, a kernel virtualization technology that provides lightweight virtualization to isolate processes and resources.

Introduction to Docker

1. Download and install Docker in Linux

1.1. Prerequisites

Docker requires a CentOS kernel higher than 3.10

Uname -r Displays the current kernel version

[root@VM-8-9-centos ~]# uname -r
3.10.0-1127.19.1.el7.x86_64
Copy the code

Update if the version is not up to scratch

Yum -y upgrade: only upgrade all packages, not upgrade software and system kernel.Copy the code

Since March 2017, Docker has been divided into two branch versions: Docker CE and Docker EE.

Docker CE is the community free edition, Docker EE is the enterprise edition, emphasis on security, but pay to use.

1.2. Uninstall the old Docker

 yum -y remove docker docker-engine docker.io containerd runc
Copy the code

1.3. Install Docker using yum

Install the necessary system tools

yum install -y yum-utils device-mapper-persistent-data lvm2
Copy the code

Add software source information

yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
Copy the code

Update the YUM cache

yum makecache fast
Copy the code

Install the Docker – ce

yum -y install docker-ce
Copy the code

Start the Docker

systemctl start docker
Copy the code

1.4. Use scripts to install Docker

curl -fsSL https://get.docker.com -o get-docker.sh
bash get-docker.sh
Copy the code

Install Docker and change the mirror source to Ali’s

curl -fsSL https://get.docker.com -o get-docker.sh
bash get-docker.sh --mirror Aliyun
Copy the code

1.5. Start the Docker process

systemctl start docker
Copy the code

1.6. Verify whether Docker is successfully installed

docker ps 
Copy the code

1.7. Mirror acceleration

Docker is overseas, and the subsequent image drawing is very slow. We can change the image source to the domestic one

Add configuration to /etc/docker-daemon. json file and create one if not

{ 
   "registry-mirrors": ["http://hub-mirror.c.163.com"] }
{
Copy the code

1.8. Mirror image source

Docker official China section

https://registry.docker-cn.com
Copy the code

netease

http://hub-mirror.c.163.com
Copy the code

Ali cloud

https://pee6w651.mirror.aliyuncs.com
Copy the code

University of Science and Technology of China

https://docker.mirrors.ustc.edu.cn
Copy the code

Delete a Docker

yum remove docker-ce
rm -rf /var/lib/docker
Copy the code

2.Hello,Docker!

2.1. Concepts of images and containers

The mirror

An image can be thought of as a special file system packaged with the runtime environment, which contains all the information needed for the container to start running, including runtime and configuration data. The image does not contain any dynamic data and its contents do not change after the build.

For example, an official Ubuntu14.04 image contains a complete set of root file systems for the Ubuntu14.04 minimum system.

The container

The relationship between an image and a container is similar to that of classes and instances in object-oriented programming. An image is a static definition, and a container is an entity of the image runtime, which can be regarded as a very lightweight virtual machine with a certain runtime environment. Containers can be created, started, stopped, deleted, and so on. When you create a container, you need to explicitly specify the image for the container. After the image is specified, the container has the runtime environment saved in the image.

For example, you can specify an image of Ubuntu14.04 for a container, which then has the Ubuntu14.04 runtime environment.

2.2.Docker uses basic procedures

1. Obtain the image

After the Docker service is installed, there is no local image, so the required image needs to be obtained first.

2. Create and start a container based on the image

Once you have the desired image, you can create and start a container based on that image, which has the runtime environment that the image contains. When creating a container, you can also set the start command of the container, which will be executed when the container is started.

3. Enter the container and execute the program.

Once the container is successfully created and started, it has an Ubuntu runtime environment. We can go inside the container and execute any application on ubuntu inside it. The “program” can be a Linux command, a shell script, or a C++ program.

2.3. Start a container and print Hello Docker

docker pull busybox:latest
docker run --name first_docker_container busybox:latest echo "Hello Docker"
Copy the code
  • First command: get an image named busybox:latest. This command will fetch an image called BusyBox: Latest from the official Docker Hub repository and download it to the host. Busybox is the smallest Linux system.
  • Second command: Create and start a container and execute the corresponding command. First, –name sets the container’s name to first_docker_container, then specifies busybox:latest as the startup image for the container, and finally sets the startup command for the container to echo “Hello Docker”. After the container starts and prints “Hello Docker,” it stops.

3. Pull the mirror

3.1. Obtaining a Mirror

Docker pull [options] < repository name > < tag >Copy the code
  • Docker pull: docker pull image command keywords;
  • [option] : command option.
  • Warehouse name: The format of the warehouse name is generally < user name >/< software name >. For Docker Hub, if the user name is not specified, the default is library, that is, the official image.
  • Label: The label is an important parameter to distinguish different versions of an image. < repository name >:< label > uniquely identifies an image. The default value is latest.

For example, pull up an official Ubuntu 14.04 image

Docker pull ubuntu: 14.04Copy the code

If the tag is empty, the default tag will be used, that is, latest. After executing the command above, the default Docker Hub will look for the repository named repoName. If it does not exist, an error message will be returned.

Untagged pulls the latest version by default

docker pull ubuntu latest
Copy the code

An error is reported when pulling a non-existent mirror

[root@localhost Desktop]# docker pull aaa
Using default tag: latest
Error response from daemon: repository aaa not found: does not exist or no pull access
Copy the code

4. Start a container

There are two ways to start the container. One is to create a new container based on the image and start it, and the other is to restart the container in the terminated state.

4.1. The first method: Create and start

The docker run command creates a container based on the specified image and starts it. The basic syntax of Docker run is as follows:

Docker run [options] Image name [command] [parameters]Copy the code

Docker run: docker create and start the container command keywords;

  • Options: Command options, the most commonly used include
    • -d Runs the container in the background and returns the container ID.
    • -I runs the container in interactive mode,
    • -t assigns a dummy input terminal to the container,
    • –name Specifies the name of the startup container.
  • Image name: specified as < repository name > : < tag >;
  • Command: sets the start command, which is executed after the container is started.
  • Parameters: Other parameters.

The work behind Docker Run

Standard operations that Docker runs in the background include:

  1. Check whether there is a specified local image, if not, download from the public repository to start;
  2. Create and start a container with an image;
  3. Allocate a file system and mount a read-write layer outside the read-only mirror layer.
  4. Bridge a virtual interface from the host’s configured bridge interface to the container.
  5. Configure one from the address poolipAddress to the container;
  6. Execute the user-specified start command;
  7. The container is terminated after execution.

Instance of a

Create and start a container with a Ubunt runtime that outputs hello Docker

Docker run Ubunt :14.04 echo 'Hello docker'Copy the code

Example 2

Create and start a container with an Ubuntu runtime called firstContainer and assign a terminal to the container to interact with the user

docker run -it --name firstContainer ubunt /bin/bash
Copy the code
  • The -i option tells Docker to keep the standard INPUT/output stream open to the container, and the -t option tells Docker to assign a pseudo-tty to the container’s standard input. –name Sets the container name for the container.
  • Docker run creates and starts a new container, so the container created by this command is not the same as the container created by the previous instance. And since the Ubuntu: Latest image already exists locally, you don’t need to download it from the Docker Hub again. Instead, you use the local Ubuntu: Latest image to build the container.
  • After starting the container, we go inside the container and interact with it at the terminal. We can tell if we are inside the container from the command prompt on the left. For example, if the command prompt on the left is root@localhost, it indicates that we are outside the container, and if the command prompt is root@fe263c9359dd/, it indicates that we are inside the container, and the container ID is FE263C9359DD. We can exit the current container through exit.

4.2. Second way: Start a terminated container

Docker run creates a new container each time. You can use the Docker start command to start a terminated container using either the container name or the container ID

Docker start [options] container [container 2...Copy the code
  • Docker start: docker start container command keyword;
  • Options: command options;
  • Container: The container that needs to be started, represented by a “container ID” or a “container name,” and if multiple containers are specified, then all of them are started.

An existing container named firstContainer is in a terminated state and can be started by docker Start firstContainer.

4.3. View container Information

If you do not know either the container name or the container ID, you can use Docker PS to view the container information.

Docker ps-a can view all containers in docker,

Docker ps -a command result

[root@VM-8-9-centos ~]# docker ps -a
CONTAINER ID   IMAGE            COMMAND                 CREATED         STATUS     PORTS          NAMES

faeacc3b5aa7   busybox:latest   "echo 'Hello Docker'"   2 minutes ago   Exited (0) 2 minutes ago  first

5799b6f4eeee   busybox:latest   "echo 'Hello Docker'"   8 minutes ago   Exited (0) 8 minutes ago  first_docker_container

Copy the code

The instance

Create and start a container named firstContainer with a BusyBox runtime environment. And print Hello World

docker busybox
docker run --name firstContainer busybox:latest echo "hello worldr"
Copy the code

5. Stop a container

5.1. Stop a container with Docker stop

Docker Stop can be used to terminate a running container. The command format is as follows:

docker stop [OPTIONS] Container [Container ...]
Copy the code

Among them:

Docker stop: docker stop container command keywords;

OPTIONS: command OPTIONS, where -t specifies how many seconds to wait before stopping the container if it has not terminated. The default wait is 10 seconds.

Container: The Container that needs to be started. This Container is represented by a Container ID or a Container name. If multiple containers are specified, all of them are started.

Stopping a container named firstContainer can be executed

docker stop firstContainer
Copy the code

After execution, the container will be in the terminated state, which can be viewed by docker ps -a.

5.2. When does a container terminate immediately after it is started?

In addition to using the Docker stop command to forcibly terminate a container, the container also terminates automatically when the container’s start command terminates. In order to

docker run --name testcontainer ubuntu echo 'hello docker
Copy the code

For example, echo ‘Hello docker’ is the start command for the container. Docker ps -a docker ps -a docker ps -a testContainer is terminated.

5.3. How can I stop the container from terminating immediately after it is started

The container will not stop if the main process of the container is not stopped.

5.3.1. Set the start command to an infinite loop
Docker run Ubuntu :14.04 /bin/sh -c "while true; do echo hello world; sleep 1; done"Copy the code

This command, after creating and starting the container, executes /bin/sh -c “while true; do echo hello world; sleep 1; Done “, since the command is never finished unless forcibly terminated, the container’s main process sh will not stop, and therefore the container will not stop either. /bin/sh -c will use the string as a command because it will not normally operate on the container and it will occupy resources.

5.3.2. Set the command to “Start the child Process that has been running”
docker run --name first_container -it ubuntu /bin/bash
Copy the code

After executing this command, after the container is created and started, a child process is started by executing /bin/bash, at which point the parent process (sh, the main process of the container) enters the sleep state. Since the sleep state is not a terminated state, the container continues to run.

The reason why the container terminates is because exit exits (terminates) the current process, /bin/bash. Since the child process is terminated, the sh main process returns to the running state. However, since there are no commands to continue, sh main process terminates and the container terminates.

Step 6 Enter a container

6.1. Several ways to enter a Docker container

1. Log in to the container using SSH.

2. Use third-party tools such as Nsenter and Nsinit;

3. Use tools provided by Docker itself

6.2. Use docker Attach to enter the inside of a container

The command

Docker Attach Container ID or container nameCopy the code

First, you create a container using Docker Run, assign a dummy terminal to it, open its standard input stream, and let it execute in the background. Docker Attach is then used to enter the container, which is actually the terminal for entering the container’s “start command”.

The container ID can be omitted as long as it represents the container. For example, 0539 is a container whose ID starts with 0539. Generally, the first four digits can uniquely identify a container.

[root@localhost]# docker run -itd ubuntu /bin/bash
0539852938cdb9538f67750d07ed8c7fa072de742d5c0c02128576f2d227ec46
[root@localhost]# docker attach 0539
root@0539852938cd:/# 
root@0539852938cd:/# ls
bin   dev  home  lib64  mnt  proc  run   srv  tmp  var
boot  etc  lib   media  opt  root  sbin  sys  usr
root@0539852938cd:/# exit
exit
[root@localhost]#
Copy the code

6.3. Access the inside of a container using Docker Exec

Docker exec [option] container name | container ID command parametersCopy the code

Example: Go into the test2 container and create a folder called HelloWorld

docker pull ubuntu
docker run -itd --name test2 ubuntu /bin/bash
docker exec test2 mkdir HelloWorld
Copy the code

6.4. Main differences between ATTACH and exec

  1. Attach directly enters the terminal of the container “Start command” without starting a new process.
  2. Exec opens a new terminal in the container and can start a new process;
  3. If you want to view the output of the container’s start command directly from the terminal, use Attach; Otherwise use exec.

7. Delete the container

7.1. Delete a terminated container

Use the docker rm container name | container ID to delete a in the end state of the container, under the condition of without parameters can only delete in the end state of the container.

steps

1. Docker ps -a view all containers

2. View the ID of the container

3. Run the docker rm container name or ID command

7.2. Delete a running container

There are two ways to remove a running container

1. Run docker stop to stop the container and run docker rm to delete it

2. Run the docker rm -f command to delete the file forcibly

Example:

1. Delete all terminated containers

docker rm $(docker ps -aq)
Copy the code

2. Delete all containers

docker rm -f $(docker ps -aq)
Copy the code

Mirror management

1. Customize an image based on Commit

The images that have been used are from the official Docker Hub, and sometimes need to be modified on the basis of these images to customize the images that meet the requirements.

Save changes to the container as an image

Docker provides a command Docker commit, which commits changes to the container as an image. In other words, a new image is created by superimposing the container’s storage layer on top of the original image (which only holds the changes made by the container). The basic syntax of docker commit is as follows:

Docker commit [options] Container name [image name]Copy the code

Among them:

Docker commit: docker pull image command keyword;

[options] : command options, where –author specifies the author, –message specifies the commit information;

1. The name of the container;

Image name: The name of the new image, specified as < repository name > : < tag >. If the setting is not displayed, it defaults to None:None. (This indicates that no mirror name is specified.)

The instance

Create a busybox:v1 image with a hello. TXT file based on busybox:latest.

docker pull busybox
docker run --name container1 busybox touch hello.txt
docker commit container1 busybox:v1
Copy the code

The pitfalls of using a COMMIT to customize images are rare in practice

1. Save a lot of unnecessary files

2.com MIT custom mirror is a black box mirror, except the producer who do not know how to produce, after a period of time may not know how to produce the author, so it is very difficult to maintain

2. Save images based on Save and load images based on load

To prevent image loss or backup; And to restore the image when needed, you need to save and load the image

2.1. Save the image to a tar package

Docker save [options] image.tar [image.tar]Copy the code

Options:

-o: specifies to write to a file, not to the standard output stream.

For example, to save the alpine: Latest image to a tar package, the following statement would be used:

Docker save alpine:latest > alpine. Tar or docker save -o alpine:lateste alpine. TarCopy the code

Save multiple images

docker save alpine:latest ubuntu:latest > image.tar
Copy the code

2.2. Load the image from the tar package

Docker load uses a tar file saved by docker Save to load the image.

Docker load [options]Copy the code

Options,

-i: reads from a tar file instead of the standard input stream.

For example, to load an image from alpine. Tar, the following statement would be used:

Docker load < alpine. Tar or docker load -I alpine. TarCopy the code

If a tar contains multiple images, they will all be loaded.

Combining these two commands with SSH and even PV, using Linux’s powerful pipeline, we can write a command to migrate images from one machine to another with a progress bar:

Docker save image < name > | bzip2 | pv | SSH < user name > @ < host name > 'cat | docker load'Copy the code

Example:

1. Busybox: Latest image is saved as a tar package.

2. After deleting busybox: Latest image, load busybox: Latest image from the tar package.

Docker pull busybox:latest Save busybox:latest > busybox:latest. Tar Delete docker rmi busybox:latest Docker load < busybox:latest.tarCopy the code

3. Import and export containers

Export 3.1.

Docker export [option] Container nameCopy the code

Options:

-o specifies to write to a file, not to the standard output stream.

For example, save Container1 to a tar package

Docker export container1 > container1.tar or docker export container1 -o container.tarCopy the code

3.2. The import

Docker import file or URL | - [images]Copy the code

File | | URL: specify the docker import objects, can be a file or a URL.

[Mirror name] : is specified as < repository name > : < label >.

For example, load an image named test:v1.0 from container1.tar

Cat container1. Tar | docker import - test: v1.0Copy the code

Docker Export and Docker Save

First, they operate on different objects. Docker Save saves an image as a tar package, while Docker export saves a container snapshot as a tar package.

Then, the container snapshot file exported by Docker export will discard all historical records and metadata information, that is, only the snapshot state of the container at that time is saved. The docker Save image storage file will hold the complete record, but also large size. As the chart below illustrates, ubuntu:test only accounts for 97.8MB while ubuntu:latest accounts for 120MB.

The instance

Save the busyboxContainer file system as a tar package.

Import a BusyBox :v1.0 image from this tar package.

docker pull busybox docker run --name busyboxContainer busybox echo "Hello,World" docker export busyboxContainer > Busybox. Tar cat busybox. Tar | docker import - busybox: v1.0Copy the code

4. Delete the mirror

Docker RMI can be used to delete local images. Rm for delete, I for image, mirror.

Before deleting an image, you need to delete the container. You can also use docker RMI -f to forcibly delete the image.

Docker rmI [options] image [image...Copy the code

Options:

-f: Forcible deletion

Image: image to be deleted. The image can be identified by image short ID, Image Long ID, Image name, or Image Digest.

You can run the following command to view information about the image, including digest

docker images -- digest
Copy the code

To delete ubuntu: Latest image, you can use the following methods:

Docker rmI 14f6; (This represents the image whose ID starts with 14f6. In general, the first four digits can be uniquely identified. If not, Docker will prompt you.)

Docker RMI 14F60031763D;

Docker rmi Ubuntu :latest

4. Image digest: Docker RMI Digest

All of the above methods can remove the Ubuntu :v1 image. But in daily life, we tend to use short ids and mirror names because they are the most convenient.

Deleting Multiple Mirrors

Delete all images from the repository named redis:

docker rmi $(docker images -q redis)
Copy the code

Deleting all Mirrors

docker rmi $(docker images -qa)
Copy the code

Before deleting an image, you need to delete the container. You can also use docker RMI -f to forcibly delete the image.

5. Build private Registry

5.1 Create a private warehouse

The Docker Hub provides mirror Resposity for creating private repositories: Registry

docker run -d -p 5000:5000 --restart=always --name registry registry:2
Copy the code

As you can see from this command, the private warehouse is operating as a container. Where –restart=always means that the Docker service is restarted or the Registry container exits.

-p maps port 5000 of the host to port 5000 of the container, so that port 5000 of the container can be accessed through IP address: 5000 of the host. (The Registry container listens on port 5000 by default); The -d parameter indicates that the system runs in the background.

– v specified private warehouse storage location, add the -v/MNT/registry: / var/lib/registry private warehouse storage location can be set to the host machine/MNT/registry.

5.2. Push the image to a private repository

1. Add a tag to the image using a Docker tag

If you want to push an image to a private repository instead of a Docker Hub, you must first use the Docker tag command to mark an image with its host name and port, as shown below. Add a label localhost:5000/ my-Ubuntu: Latest to the Ubuntu: Latest image.

docker tag ubuntu:latest localhost:5000/my-ubuntu
Copy the code

Use docker push to push the image to a private repository

The docker push command can be used to push an image to the repository. By default, the image is pushed to the official repository docker Hub, but pushing an image “marked with hostname and port” will be pushed to a private repository.

docker push localhost:5000/my-ubuntu
Copy the code

5.3. Pull image from private warehouse

Docker pull can pull an image from the repository, and by default, from the official repository. When I want to pull my my-Ubuntu: Latest image from a private repository. Simply execute the following command.

docker pull localhost:5000/my-ubuntu
Copy the code

5.4. View or delete mirrors in the private vault

The Registry image provided by Docker does not provide the command to view the image and delete the image, but there are third-party software that can provide these functions, such as Harbor.

5.5. Delete private warehouses

A private warehouse is essentially a container, so deleting a private warehouse is to delete the container corresponding to the private warehouse. We can use docker rm -f to delete it forcibly, but after this deletion, the image stored in the private repository will not be deleted. If you want to delete the private repository as well as the image, you need to add the -v parameter, also known as docker rm -f -v. For example, to delete a local private warehouse, run the following statement:

docker rm -vf myregistry
Copy the code

The instance

Docker run -d -p 55:5000 --restart=always --name myregistry registry:2 2 Docker pull Ubuntu 3. Use the Docker tag to tag Ubuntu with localhost: latest localhost:5000/ my-Ubuntu :latest 4. Docker push localhost:5000/ my-Ubuntu :latest 5 Delete docker rmi localhost:5000/ my-Ubuntu: Latest 6. Latest image docker pull localhost:5000/ my-Ubuntu 7 from private repository Docker rm -vf myregistry docker rm -vf myregistryCopy the code

Four, Dockerfile

1. The first Dockerfile

1.1. Dockerfile profile

Dockerfile describes the steps of assembling images, of which each command is executed independently, except the FROM instructions, other each instruction in a specified on the basis of the generated image execution, execution of the mirror will generate a new layer, above new mirror cover in the original image layer, thus formed a new image. Addresses the previously mentioned issues of non-repeatability, mirror build transparency, and volume.

1.2.Dockerfile basic two instructions: FROM and RUN

FROM specifies the base image; Format: FROM< mirror name > or FROM< mirror name >:< label >.

The function of the FROM directive is to provide a base mirror for subsequent directives, so a valid Dockerfile must have the FROM directive as the first non-annotation directive. If the tag parameter in the FROM command is empty, the tag is latest by default. If the parameter image or tag specifies that the image does not exist, an error is returned.

RUN Runs a command. Format: RUN < command >

The RUN command is used to execute command line commands. The RUN command creates a container based on the image created by the previous command and runs the command inside the container. The new container is submitted as a new image at the end of the command, and the new image is used by the next instruction in the Dockerfile.

1.3. Build an image using Dockerfile

steps

1. Create an empty file and access it

2. Create a file named Dockerfile and complete the content as required

3. Build a docker build-t testimage image named testimage using dockerfile.

-t Specifies the name of the new mirror

You can’t lose a decimal point at the end of the command

The instance

Use Dockerfile to build an image called TEstimage with the Ubuntu: Latest runtime environment and create a Linux folder in the root directory

mkdir Ubuntuimage
cd Ubuntuimage
touch Dokerfile
vim Dockerfile
#Add the following
FROM ubuntu:latest
RUN mkdir Linux

docker build -t testimage .
Copy the code

When writing a Dockerfile, it is important to keep in mind that each layer of the image will not change after it is built, and any changes on the latter layer will only happen on your own layer. Deleting a file from the previous layer does not actually delete the file from the previous layer, but only marks the file as deleted at the current layer. This file will not be seen when the final container runs, but it will actually follow the image.

Docker build, COPY, and ADD

2.1.docker build command description

After the Dockerfile is created, you can use the docker build command to build an image from the Dockerfile.

Docker build [option] context path | URLCopy the code

Options:

-t: specifies the mirror name.

-f: specifies the Dockerfile. If this parameter is not specified, the Dockerfile in the current folder is used by default.

In addition to building locally, Docker builds can also be built from urls, such as directly from Git repo.

2.2.COPY command and ADD command

COPY command syntax:

COPY < source path > < destination path >Copy the code

Syntax of the ADD directive:

ADD < source path > < destination path >Copy the code

The COPY and ADD directives are very similar in function, but ADD some functionality to the COPY path. For example, the source file path of ADD can be a URL, in which case the Docker will download the file to which the URL points.

If the source file path is a tar file, run the COPY command to COPY the source file to a specified directory. The ADD command automatically decompresses the compressed file to a specified directory.

The instance

Build an image called BusyBox :v3 with Dockerfile as follows:

Ubuntu based image; Copy dir1.tar in the directory decompressed and extracted to/of the new image. Build an image called Ubuntu:v3 based on the Dockerfile using the Docker build.

mkdir ubuntuImage
cd ubuntuImage
mkdir dir1 && -cvf dir1.tar dir1 && rm -rf dir1
touch Docfile
vim Dockerfile
#Content added to the Dockerfile file
FROM ubuntu:latest
ADD ./dir1.tar /
#Exit Vim and build an image called Busybox :v3 with the Dockerfile
docker build -t ubuntu:v3 .
Copy the code

3.CMD and ENTRYPOINT

CMD and ENTRYPOINT are common Dockerfile directives that specify container start commands for images.

Difference between CMD and Entrypoint

Thing in common:

Specifies the command to execute when starting the container. There can be only one CMD/ENTRYPOINT command per Dockerfile. If multiple commands are specified, only the last command will be executed. The usage supports both exec and shell and is similar

The difference between:

CMD: specifies the command to run when the container is started. The command specified by CMD in the image is overwritten

ENTRYPOINT: The command specified to run when the container is started does not override the command of ENTRYPOINT in the image

The instance

Requirements:

1. Use Busybox: Latest as the base image. 2. Set the startup command to df -th. The df command cannot be overwritten, but -th can be overwritten. 3. Use docker build to build an image named mydisk:v1 based on the Dockerfile.

mkdir busyboxImage
cd busyboxImage
touch Dockerfile
echo "FROM busybox:latest" > Dockerfile
echo 'ENTRYPOINT ["df"]' >>Dockerfile
echo 'CMD ["-Th"]' >>Dockerfile
docker build -t mydisk:v1 .
Copy the code

4.ENV, EXPOSE, WORKDIR, ARG instructions

WORKDIR instruction

WORKDIR sets the working directory for other instructions; Format: WORKDIR < working directory path >.

WORKDIR /tmp
Copy the code

The WORKDIR directive sets the working directory (or current directory) for any of the RUN, CMD, ENTRYPOINT, COPY, and ADD directives in the Dockerfile; If the directory corresponding to WORKDIR does not exist, it will be created automatically.

EXPOSE instruction

ENV Sets the environment variable. Format: ENV or ENV =;

This directive simply sets environment variables, which can be used by any subsequent directive or runtime application.

ENV STR ="Hello,World" ENV APACHE_HOME /var/ TMP /apache-tomcat-8.0.45Copy the code

ARG instruction

ARG construction parameters; Format: ARG < parameter name >[=< default value >];

ARG is similar to ENV in that it can be used directly by other directives, but it is not an environment variable, which means that there will be no ARG variable in the future container runtime.

When to use ARG and when to use ENV? If you want to save as an environment variable, use ENV; If you only want to use it temporarily in a Dockerfile, use ARG.

EXPOSE instruction

EXPOSE port; EXPOSE < Port 1> [< Port 2>…]

The EXPOSE directive states that the runtime container provides a service port. This is just a claim, and the application does not open that port at runtime because of this claim. If you want to EXPOSE the container’s ports, you must specify either the -p parameter in the Docker run to EXPOSE the ports or the -p parameter to EXPOSE all of the exposed ports.

Writing such a declaration to a Dockerfile has two benefits

1. Help the mirror user understand the daemon port of the mirror service to facilitate mapping configuration.

2. When random port mapping is used at runtime, that is, docker run -p automatically randomly maps EXPOSE ports.

The instance

Requirements:

Use BusyBox: Latest as the base image; Declaration exposed 3000 port; Set var1=”test” to the environment variable; Set the working directory to/TMP and create a 1.txt file in the working directory. Based on the Dockerfile file, build an image named tESTIMage :v1.

mkdir busyboxImage
cd busyboxImage
touch Dockerfile
echo "FORM busybox:latest" >Dockerfile
echo "EXPOSE 3000" >> Dockerfile
echo "ENV var1=test" >> Dockerfile
echo "WORKDIR /tmp" >>Dockerfile
echo "RUN touch 1.txt" >> Dockerfile
Copy the code

5.ONBUILD and VOLUME directives

ONBUILD instruction

ONBUILD adds a trigger to be executed in the future

Format: ONBUILD < other instructions >

ONBUILD is a special command that is followed by other commands, such as RUN, COPY, etc., that are not executed during the current image build. It is executed only when the current mirror is used to build the next level of the mirror. After the mirror is built, the trigger instructions are cleared and will not be inherited by subsequent mirrors.

The VOLUME directive defines an anonymous VOLUME. Format: VOLUME [“< path 1>”, “< path 2>”… Or VOLUME < path >;

When a container is running, no write operations should occur on the container storage layer. For applications that need to store dynamic data in database classes, database files should be stored in data volumes.

6. Caching mechanism for image construction

Caching mechanism for image build

During image building, Docker steps the instructions in your Dockerfile in the order specified. With each instruction checked, Docker looks for an existing image in its cache that can be reused, rather than creating a new (duplicate) image. If you don’t want to use caching, you can use the –no-cache = true option in the Docker build command.

V. Data volume operations

1. Create a data volume

After Docker1.9, Docker provides a new command: Docker volume, which is used to create, view, and delete data volumes. The traditional docker run-v method of creating a data volume remains.

Method of creating a data volume

1. Use docker Volume Create to create a data volume and specify the name of the data volume.

docker volume create --name vo1
Copy the code

2. When creating a container, add the -v label to create a data volume

docker run -itd -v/data ubuntu /bin/bash
Copy the code

3. When creating a container, specify the name of the data volume and mount it to the container directory

docker run -itd -v vo2:/data ubuntu /bin/bash
Copy the code

Daily work is generally used in the third way, create a container to specify the name of the data volume, and mount to the specified directory

The instance

Create a data volume named vo1 and mount the data volume to the /dir1 directory of container1.

docker pull ubuntu
docker run -v vo1:/dir --name container1  ubuntu
Copy the code

2. Mount and share data volumes

2.1. Mount data volumes

By default, when a data volume is created, a directory named Data Volume name is created in /var/lib/docker-volume/ on the host and the data volume content is saved in the /_data directory under this directory. In other words, the contents of the data volume are stored in /var/lib/docker-/volume/data. The contents of the data volume are always consistent with the mount point of the container. You can specify a data volume name. If you do not specify a data volume name, the system randomly generates a data volume name.

Mount the host directory

Mount /host/dir to /container/dir of the container.

docker run --name vocotainer1 -v /host/dir:/container/dir ubuntu
Copy the code

Note that the host directory and the container directory must use absolute paths. If the /host/dir directory does not exist on the host, an empty folder is created. All files and folders under /host/dir can be accessed in the container under /container/dir. If the /container/dir folder already exists in the image, all contents in the folder are deleted to ensure that the folder is the same as the folder on the host.

Create multiple data volumes simultaneously

It is also possible to create multiple data volumes simultaneously while mounting, for example, the following command creates two data volumes co3 and co4

docker run --name vocotainer2 -v co3:/data -v co4:/dir1 ubuntu
Copy the code

Share data volumes with other containers

When using docker Run to create and start a new container, you can also use the –volumes-from tag to share data volumes with an existing container. The following command creates a container named vocotainer3 and shares the data volume with voContainer1. Since the mount point for voContainer1 is on /container/dir, the mount point for vocotainer3 will also be /container/dir.

docker run --name vocotainer3 --volumes-from vocontainer1 ubuntu
Copy the code

In general, if you have files that need to be shared by multiple containers, a common practice is to create a data container (which is used only to share data and not for any other purpose) with which other containers share data volumes.

The instance

Requirements:

Create a container named container1 and mount the /dir1 directory of the localhost to /codir1. Create a container named Container2 and share the data volume with Container1.

docker pull ubuntu
docker run -v /dir:codir --name container1 ubuntu
docker run --volumes-from container1 --name container2 ubuntu
Copy the code

3. View the name of the data volume

3.1. View details about the data volume

Viewing a data volume Create a data volume without specifying the name of the data volume

docker run -v /data --name vocontainer1 ubuntu
Copy the code

Viewing data Volumes

docker inspect --type container vocontainer1
Copy the code

It outputs the ID, creation time, name, and many other parameters.

3.2. View only the data volume name

Parse Docker Inspect with –format

Docker inspect - type container -- format = '{{range. Mounts}} {{. Name}} {{end}}' container Name | container IDCopy the code

View the data volume name for voContainer1

docker inspect --type container --format='{{range .Mounts}}{{.Name}}{{end}}' vocontainer1
Copy the code

4. Delete the data volume

The first way

The data volume will fail to be deleted if it is still being used by other containers. The data volume will be deleted if it is not being used by other containers

Docker Volume Rm Data volume nameCopy the code

The second way

When a container is deleted, the data volume is deleted in two cases:

1. The name of the data volume is not specified when the data volume is created

The data volume will fail to be deleted if it is used by another container, and will be deleted if it is not used by any container

2. Specify the data volume name when creating the data volume

Deleting a container only disconnects the data volume from the container. To delete a data volume, use the first method

Docker rm -v Specifies the container name or IDCopy the code

The third way

The –rm tag is specified when the container is created, and when the container is in the “terminated state”, the container will be deleted and the data volume corresponding to the container will be attempted to be deleted.

If no data volume name is specified, the corresponding data volume will be deleted. If the data volume name is specified, it only removes the association between the data volume and the container. To delete the data volume, use the first method.

Delete unnecessary data volumes

If you run the following command, all data volumes that are not being used by the container will be deleted.

docker volume prune
Copy the code

The instance

docker pull ubuntu
docker run -v vo4:/data --name container1 ubuntu
docker rm -v container1
docker volume rm vo4
Copy the code

5. Back up and restore data volumes

1. Back up the data volume

First create a container voContainer1, create a data volume named db1, and attach the data volume to the container’s /dbdate directory.

docker run -v db1:/dbdate --name vocontainer1 ubuntu
Copy the code

Run –volumes-from to create a new container that shares the dbdata mount directory with container1 and the current directory on the host to the /backup directory

docker run --volumes-from container1 -v $(pwd):/backup ubuntu tar -cvf /backup/backup.tar /dbdata
Copy the code

After the container is started, the tar command is used to compress the dbdata directory and save it in the /backup/backup.tar file. The current directory of the host is mounted in the /backup directory of the container, but the contents of the two mounted directories are the same. So the contents of the DBContainer1 data volume are compressed and stored in the current directory of the host machine.

2. Restore a data volume

Create a container containing container2 with an empty data volume mounted to the directory/dbData and named db1.

docker run -v db1:/dbdata --name container2 ubuntu /bin/bash
Copy the code

Then go to the host directory where backup.tar was stored and run the following command to create a new container that shares the dbdata mount directory with container2 and mount the current host directory to /backup of the container.

docker run --volumes-from container2 -v $(pwd):/backup busybox tar -xvf /backup/backup.tar -C /dbdata
Copy the code

To start the container, run the tar command to decompress the backup file backup.tar to the /dbdata directory. Since the container shares a data volume with Container2, the backup file backup.tar is decompressed to the /dbdata directory of Container2. Because container2 mounts a data volume named DB1 to/dbData, it essentially restores the db1 data volume.

Example: Back up and restore data volume VO1

Create vo1 data volume and add 1.txt to the data volume

docker pull ubuntu
docker run --name vocontainer -v vo1:/dir1 ubuntu touch /dir1/1.txt
Copy the code

Backup the vo1 data volume to /newback on the host, mount the container’s /backup path to it, and package the /dir1 folder in the container to /backup/backup.tar

docker run --volumes-from vocontainer1 -v /newback:/backup ubuntu tar -cvf /backup/backup.tar  /dir
Copy the code

Delete all containers and the data volumes it uses

docker rm -vf $(docker ps -aq)
docker volume rm vo1
Copy the code

Create a vo1 data volume this time

docker run -itd --name vocontainer2 -v vo1:/dir1 ubuntu /bin/bash
Copy the code

Restore the data stored in the backup file on the host machine to the/of voContainer2

docker run --volumes-from vocontainer2 -v /newback:/backup ubuntu tar -xvf /backup/backup.tar -C /
Copy the code