This article is for the introduction of Docker learning notes, do not understand can directly watch the learning video link at the end of the article, this article is to sort out the notes of the video, convenient for future work to find, Docker knowledge points in this article is enough for development.

Docker installation

The basics of Docker

Three concepts

Image:

An image can be likened to a VM image or a software installation package. For example: Redis image, Nginx image, Ubuntu image, etc. Images are the basis for Docker creation. Developers can download and obtain the image that has been set up on the network to directly develop the application.

The most intuitive understanding is that the image is like the software installation package, the software installation package has no impact on the software installation package, the software installation package can still be used on another machine.

Container:

A container is like a lightweight sandbox that Docker uses to run and isolate applications. Containers are application instances created from images, similar to the relationship between classes in Java and objects instantiated through classes. Each container has its own operation cycle and is isolated from each other, just like objects from Java class instances.

The mirror itself is read-only and cannot be modified. When the container starts from the image, it actually generates a read-write layer at the top of the image

To put it bluntly, containers are like installed software that can be turned on or off at any time.

Repository:

A warehouse is a place to put a lot of things, so a Docker warehouse is a centralized place to store image files. Each Docker warehouse stores a set of Docker images, which are distinguished by tag. The concept of Docker warehouse is roughly the same as Git idea, because Docker is designed by referring to Git for construction and development in many places, which makes the use of Docker more convenient and familiar to developers.

Install the docker

The environment that

If you use CentOS7.x of Linux, you can install VMS by yourself or buy alicloud ECS cloud services. Most of the production environments are CentOS versions, so it is recommended.

Installation steps

# 1. Uninstall the old version of Docker. Docker \ docker-client \ docker-client-latest \ docker-common \ docker-latest \ sudo yum remove docker \ docker-client \ docker-client-latest \ docker-latest-logrotate \ docker-logrotate \ docker-engine # 2. Sudo yum install -y yum-utils # 3 Equipment mirror warehouse sudo yum - config - manager \ - add - repo \ https://download.docker.com/linux/centos/docker-ce.repo (this is the overseas warehouse, Not recommended) yum - config manager \ - add - repo \ https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo (this is ali cloud image warehouse, # 4. Update yum package index yum Makecache Fast # 5. Sudo yum install docker-ce docker-ce-cli containerd. IO # 6 Docker sudo systemctl start docker # 7 Docker version # 8. Hell-worl test docker run hell-worldCopy the code

Ali Cloud image acceleration

  1. Ali cloud into the console

2. Copy the aliyun image acceleration address

Docker common command

Basic commands

Docker info # Check the system information of docker, including the number of images and containers docker [command] --help # helpCopy the code

The mirror command

Docker images # select * from docker images # select * from docker images # select * from docker images # select * from docker images # select * from docker imagesCopy the code

Docker image View all commands for images

Commands: build Build an image from a Dockerfile history Show the history of an image import Import the contents from a tarball to  create a filesystem image inspect Display detailed information on one or more images load Load an image from a tar archive or STDIN ls List images prune Remove unused images pull Pull an image or a repository from a registry push Push an image or a repository to a registry rm Remove one or more images save Save one or more images to a tar archive (streamed to STDOUT by default) tag Create a tag TARGET_IMAGE that refers to SOURCE_IMAGECopy the code

Container order

Docker rm docker rm docker rm docker rm docker rm docker rm docker rm docker rm docker Docker stop docker kill docker kill docker exec docker attach docker Docker commit # create a new image based on the current container docker logs # view log # 2. Docker Top Container ID Docker stats Container ID # 3. Docker inspect Container IDCopy the code

Some important commands

Docker run starts a container

Docker run -d --name -p 8090::80 docker run -d --name -p 8090::80Copy the code

Docker Run restricts container use of content resources

# -e ES_JAVA_OPTS="xms128m -xmx128m"Limit the memory usage of ES heap host machine to a maximum of 128Mdocker run -d --name elasticsearch --net somenetwork -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" -e ES_JAVA_OPTS = "xms128m - xmx128m" elasticsearch: 7.6.2Copy the code

Docker CP copies container contents

Docker cp Container ID: Inside path Host destination pathCopy the code

Docker exec enters the container

#Enter the container in interactive mode (if the container is not started, enter and exit the first time, the container may stop)Docker exec -it Container ID /bin/bashCopy the code

Docker attach into container

Docker Attach Container ID#Docker attach and dockerexecThe difference between?
# docker exec After entering the current container, open a new terminal that can be operated in. (common)
# docker attach Enter the terminal where the container is executing
Copy the code

Docker container Displays all commands for a container

Commands:
      attach      Attach local standard input, output, and error streams to a running container
      commit      Create a new image from a container's changes
      cp          Copy files/folders between a container and the local filesystem
      create      Create a new container
      diff        Inspect changes to files or directories on a container's filesystem
      exec        Run a command in a running container
      export      Export a container's filesystem as a tar archive
      inspect     Display detailed information on one or more containers
      kill        Kill one or more running containers
      logs        Fetch the logs of a container
      ls          List containers
      pause       Pause all processes within one or more containers
      port        List port mappings or a specific mapping for the container
      prune       Remove all stopped containers
      rename      Rename a container
      restart     Restart one or more containers
      rm          Remove one or more containers
      run         Run a command in a new container
      start       Start one or more stopped containers
      stats       Display a live stream of container(s) resource usage statistics
      stop        Stop one or more running containers
      top         Display the running processes of a container
      unpause     Unpause all processes within one or more containers
      update      Update configuration of one or more containers
      wait        Block until one or more containers stop, then print their exit codes
Copy the code

Docker command:

3, Docker image principle

What is a mirror image

An image is a lightweight, executable independent software guarantee that packages a software runtime environment and software developed based on the runtime environment. It contains everything needed to run a piece of software, including code, runtime libraries, environment variables, and configuration files

Docker image loading principle

UnionFs: UnionFs is a layered, lightweight, and high-performance file system that allows changes to the file system to be layered on top of each other as a single commit. Unite several directories into a single virtual filesystem. The Union file system is the basis for Docker images. Mirror can be inherited by stratified, based on the base image (no parent mirror), mirror can make all kinds of specific application characteristics: a load multiple file system at the same time, but from the outside, it seems, can only see a file system, the joint load add up the layers of the file system, so the final file system will contain all the underlying files and directories

Docker’s image actually consists of a layer upon layer of file systems, such as UnionFS. Boots (Boot File System) mainly includes bootloader and Kernel. Bootloader is mainly bootloader plus Kernel. Bootfs file system will be added when Linux starts up. This layer is the same as our typical Linux/Unix system, containing the Boot loader and the kernel. After boot is loaded, the entire kernel is in memory. At this time, the use of memory has been transferred to the kernel by bootFS. At this time, the system will uninstall bootFS. Rootfs (root file System) on top of bootfs. It contains standard directories and files such as /dev,/proc,/bin, and /etc in a typical Linux system. Rootfs is a variety of operating system distributions, such as Ubuntu, Centos, etc

For a compact OS,rootfs can be small and only need to package the most basic commands, tools, and libraries, because the underlying kernel directly uses the Host kernel, and only need to provide rootfs. This shows that boots is basically the same for different Linux distributions and rootfs differ, so different distributions can share bootfs.

Virtual machine is minute, container is second!

Docker layering technology

When downloading images through Docker pull, it is found that docker is downloaded layer by layer. Using the Docker image inspect command, you can see image layers.

[root@linux ~]# docker pull redis
Copy the code

[root@linux ~]# docker image inspect redis
Copy the code

The biggest benefit, I think, is resource sharing! For example, if multiple images are built from the same Base image, the host only needs to keep one Base image on disk and load only one Base image in memory, so that all containers can be served, and each layer of the image can be shared.

Commit the mirror

Docker commit The image commit container becomes a new copy (image)

# -a="Submitter" -m="Comments on submitted content"Tomcat02 :1.0 -> New image name: new image versionDocker commit -a="ziyu" -m="add webapps app" container ID tomcat02:1.0Copy the code

Practical test

#1. Download the Tomcat imageStart a default tomcat docker run -d -p 8090:8080 tomcat # 3. Docker exec-it container id /bin/bash # 4, docker exec-it container id /bin/bash # 4 Modify the start tomcat content, copy/usr/local/tomcat/webapps. The content of the dist next to/usr/local/tomcat/webapps CD/usr/local/tomcat webapps/cp - r. Dist / *  webapps/ # 5. Docker commit -a="ziyu" -m="add webapps app" Container ID New image name: new image version numberCopy the code

Container data volume

Container data volume technology

The idea behind Docker is to package the data and the environment into a mirror image, so that if the data is in the container, and we delete the container, the data is lost. In a production environment, we don’t want data to be lost. Therefore, data needs to be persisted locally (the host).

A technique of data sharing between the container and the local, that is, the data generated in the container is synchronized to the local, this technique is called container data volume technology. In other words, the directory in the container is mounted to the directory in the Linux system to ensure that the data in the container is synchronized to the directory in the Linux system.

Conclusion: Container persistence and synchronization operations, containers can also share data!

Using a Data Volume

Mode 1: Run the command directly to mount -v

Docker run -v Host directory: container directory centos /bin/bash#test
docker run -it -v /home/ceshi:/home centos /bin/bash

#When starting up, you can run the following command to view the mount relationshipDocker inspect Container IDCopy the code

Description:

  1. Even if the container is stopped and the file in Linux is modified; The container is then restarted and can still be synchronized to the modified content;

  2. If the container is deleted, data mounted to the directory on the Linux system will not be lost.

Named and anonymous mounts

#Anonymous mountDocker run -d -p --name nginx01 -v /etc/nginx nginx # docker inspect container ID # Docker run -d -p --name nginx02 -v juming /etc/nginx niginx Inspect jumingg-ninx # how to determine whether to mount named or anonymous, Docker run -d -p --name nginx02 -v: docker run -d -p --name nginx02 -v: docker run -d -p --name nginx02 -v: docker run -d -p --name nginx02 -v Juming-nginx :/etc/nginx:ro nginx # read-only docker run -d -p --name nginx02 -v juming-nginx:/etc/nginx:rw nginx # Read-write # ro Seeing ro means that the path can only be accessed from the host, not from the container itselfCopy the code

DockerFile

A Dockerfile is a build file used to build a Docker image.

This script can be used to generate the image, which is a layer by layer, script command by command, each command is a layer

#Create a dockerfile file, preferably with dockerfile
FROM centos

VOLUME ["volume01","volume02"]

CMD echo "---end---"

CMD /bin/bash

#Dockerfile build command
docker build -f /home/docker-test-volume/dockerfile1 -t ziyu/centos .
Copy the code

Note: pay attention to the writing of the red line, can not be preceded by /, after. Cannot little.

 #Run the image you createdDocker run -it Container ID /bin/bashCopy the code

VOLUME ["volume01","volume02"] #Copy the code
#Check the path to which the volume is mountedDocker inspect Container IDCopy the code

Explanation: This method is used a lot, because we usually build our own mirror image;

If the image is not attached to a volume during image construction, manually attach the volume to the image. -v Volume name: Inside container path
#Docker02 mount docker01; Docker02 can synchronize data with Docker01
docker run -it --name docker02 --volumes-from docker01 ziyu/centos

#Container-volume technology, data is backed up and copied to each other, rather than shared
Copy the code

4. Write your own Dockerfile

Dockerfile build steps

  1. Write a dockerFile file
  2. Docker builds into an image
  3. Docker run runs the image
  4. Docker Push release image (DockerHub, Ali Cloud image warehouse)

Dockerfile is development oriented, we publish projects generally do an image, is to write a Dockerfile file.

Company development and deployment process:

  1. Dockerfile: the build file that defines all the steps (source code)
  2. DockerImages: The images generated by the Dockerifle build, and the final product released and running
  3. Docker container: The container is the service that the image runs on.

Dockerfile instructions

MAINTAINER # Who writes the image, name + email RUN # Command ADD # Steps needed to RUN an image build: WORKDIR # WORKDIR # VOLUME # mount # EXPOST # exposed port config CMD # specify the command to be sent when the container is started. Only the last command will be valid and can be replaced by ENTRYPOINT # specify the command to be run when the container is started. You can append the ONBUILD command to run ONBUILD when building an inherited Dockerfile. Trigger instruction. ENV # set environment variables such as ls -a docker run -l CMD instead of -l, the execution will not be successfulCopy the code

Practical test

Create your own centos

 #1. Compile a dockerfile file
[root@linux dockerfile]# cat mydockerfile 
FROM centos
MAINTAINER ziyu<[email protected]>

ENV MYPATH /usr/local
WORKDIR $MYPATH

RUN yum -y install vim
RUN yum -y install net-tools

EXPOSE 80

CMD echo $MYPATH
CMD echo "----end----"
CMD /bin/bash

#2. Build an image using a file
#Command docker build -f dockerfile file path -t New image name: indicates the image version.Docker build -f myDockerfile -t mycentos:0.1
#3. Test run
docker run -it mycentos
Copy the code

We made our own image, running the effect:

View mirror build history

Docker History Image IDCopy the code

CMD is different from ENTRYPOINT

CMD # specifies the command to run when the container is started. Only the last command is valid and can be substituted. ENTRYPOINT # specifies the command to run when the container is startedCopy the code

Test the CMD

Test the ENTRYPOINT

If you run the last command above, the image built by this command will work fine.

Publish to a remote repository

Ali cloud is generally used within the company, and the release process refers to Ali Cloud

Docker FAQs

  1. Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running

Solution: Forgot to start docker service, start command: service docker start

References

The latest hyper-detailed version of Docker tutorial is easy to understand