编程知识 cdmana.com

1. Introduction to docker, command, container, image, data volume, dockerfile, installation of common software and push to alicloud

One 、docker Introduce

1、docker What is it?

  • A product from development to online , Slave operating system , To the operating environment , Then to application configuration . As a development + We need to care a lot about the cooperation between operation and maintenance , This is also a problem that many Internet companies have to face , Especially after iterations of various versions , Compatibility of different versions of environment , It is a test for operation and maintenance personnel , Environment configuration is so troublesome , Change a machine , We're going to do it again , Laborious and time-consuming . A lot of people think , Can we solve the problem fundamentally , Software can be installed with environment ? in other words , During installation , Copy the original environment as like as two peas. . Developer leverage Docker Can eliminate collaboration when coding “ It works fine on my machine ” The problem of . The original deployment method is that developers only package the program and send it to the operation and maintenance personnel , There are differences between the development environment and the production environment ,docker You can package the running environment , Arrive to make the development environment and production environment consistent
  • Docker Is based on Go Cloud open source project implemented by language
  • Docker The main objectives of “Build,Ship and Run Any App,Anywhere”, That is, through the encapsulation of application components 、 distribution 、 Deploy 、 Life cycle management such as operation , User's APP( It could be a WEB Application or database application, etc ) And its operating environment can achieve “ One time encapsulation , Run anywhere ”
  • Linux The emergence of container technology solves such a problem , and Docker It's based on it . Run the application on Docker On top of the container , and Docker Containers are consistent on any operating system , This enables cross platform 、 Cross server . Just configure the environment once , Switch to another machine and you can deploy it with one click , Greatly simplified operation
  • Solve the problem of running environment and configuration software container , Container virtualization technology that facilitates continuous integration and facilitates overall release

2、docker advantage

  • Virtual machine is a solution with environment installation , Simulate another operating system on one operating system , Run the program on the simulated operating system , The application has no perception , For the underlying operating system , A virtual machine is a file that doesn't need to be deleted , Perfect analog hardware , The relationship between operating system and Application
  • Docker Compared to virtual machines
    • Virtual machine and docker Need to run on the underlying operating system , Virtual machines use virtual machine management software ( for example :VMware), and docker Depending on its daemons
    • Virtual machine management software will create a complete machine ( Including the operating system , Hardware storage, etc ), The required application processes are then run on the system ; and docker The application process inside runs directly in the host's kernel , There is no kernel of its own in the container , And there is no hardware virtualization , Therefore, the container is lighter than the traditional virtual machine, and only one container application will be virtualized , The bottom layer uses the host's hardware , Each container is isolated from each other , Each container has its own file system , Processes between containers don't affect each other , Be able to distinguish computing resources
    • Virtual machine takes up a lot of resources 、 There are many redundant steps 、 Slow start , and docker Less resources , It's easy to operate , Fast start
    • docker A build 、 Run anywhere
      • Faster application delivery and deployment
      • More convenient upgrade and expansion
      • Simpler system operation and maintenance
      • More efficient use of computing resources
  • Related websites

3、docker install

3.1、 Prerequisite

  • centos install docker need 6.5 Above version
  • centos Only the content in the distribution supports ,centos7 requirement 64 position , Kernel version 3.10 above ,centos6.5 requirement 64 position , Kernel version 3.6.32-431 above
  • uname -r View kernel version
  • cat /etc/redhat-release Check the system

3.2、docker framework

  • explain

    • docker Both the client and the client are docker The daemons of
    • Docker Mirror image (Image) It's a read-only template . Images can be used to create Docker Containers , A single image can create many containers
    • Docker Use containers (Container) An application or group of applications running independently . A container is a running instance created with a mirror . It can be started 、 Start 、 stop it 、 Delete . Each container is isolated from the other 、 Secure platform . Think of the container as a simple version of Linux Environmental Science ( Include root User permissions 、 Process space 、 User space and cyberspace, etc ) And the applications running in it . The definition and mirror as like as two peas are identical , It's also a unified perspective of many layers , The only difference is that the top layer of the container is readable and writable .
    • Warehouse (Repository) It's a place for centralized storage of image files . Warehouse (Repository) And warehouse registration server (Registry) There is a difference . Warehouse registration servers often store multiple warehouses , Each warehouse contains multiple images , Each image has a different label (tag), Warehouses are classified as open warehouses (Public) And private warehouses (Private) Two forms . The biggest open warehouse is Docker Hub(https://hub.docker.com/), A large number of images are stored for users to download . Domestic open warehouses include Alibaba cloud 、 NetEase, cloud, etc.
    • Easy to understand : A mirror image is a class , A container is an object , A class can create multiple objects , They don't influence each other , Warehouse and maven equally , Where to store the mirror image

3.3、docker install

  • docker Please refer to the official website for installation , There are two ways , Automatic installation, manual installation
uninstall
  • sudo yum remove docker
    docker-client
    docker-client-latest
    docker-common
    docker-latest
    docker-latest-logrotate
    docker-logrotate
    docker-engine
Automatic installation
  • yum install docker
  • Verify that the installation was successful :docker version
Manual installation
  • 1. install gcc relevant :yum -y install gcc,yum -y install gcc-c++

  • 2. Install required packages yum-utils Provides yum-config-manager , also device mapper The storage driver needs device-mapper-persistent-data and lvm2

    • sudo yum install -y yum-utils device-mapper-persistent-data lvm2
  • 3. Set up warehouse ( Pay attention to the choice of domestic , Abroad is very slow )sudo yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

  • 4. Install the latest version Docker Engine-Community and containerd, Or install a specific version

    • sudo yum install docker-ce docker-ce-cli containerd.io
      • centos8 Installation error Problem: package docker-ce-3:19.03.14-3.el7.x86_64 requires containerd.io >= 1.2.2-3, but none of the providers can be installed Solution
    • 5. start-up docker:sudo systemctl start docker
    • 6. function Hello world:sudo docker run hello-world If you can't find it locally, you can't download it from the library automatically
    • 7. Configure alicloud image Accelerator

      • Get the accelerator link address :https://cr.console.aliyun.com/cn-hangzhou/instances/mirrors
      • Create directory :mkdir -p /etc/docker
      • create profile :vim /etc/docker/daemon.json And write {"registry-mirrors": ["https://{ Your own code }.mirror.aliyuncs.com"]}
      • restart docker:sudo systemctl daemon-reload,sudo systemctl restart docker
Boot from boot
  • systemctl start docker.service
  • systemctl enable docker.service
  • systemctl grep docker see docker State of process

4、docker principle

  • Docker It's a Client-Server System of structure ,Docker The daemons are running on the host , And then through Socket Connection access from client , The daemons receive commands from the client and manage the containers running on the host . Containers , It's a runtime environment , It's the container we mentioned earlier .
  • docker There are fewer layers of abstraction than virtual machines . By docker Unwanted Hypervisor Realize hardware resource virtualization , Running on the docker The programs on the container directly use the hardware resources of the actual physical machine . So in CPU、 Memory utilization docker There will be a clear advantage in efficiency .
  • docker Using the kernel of the host , Without the need for Guest OS. therefore , When you create a new container ,docker No need to reload an operating system kernel like a virtual machine . Still avoid seeking 、 Loading the operating system kernel returns a time-consuming and resource consuming process , When you create a new virtual machine , Virtual machine software needs to be loaded Guest OS, Back to the new process is at the minute level . and docker Due to the direct use of the host operating system , It omits the process of returning , So create a new docker The container only takes a few seconds .

Two 、docker Common commands

1、 Help order

  • View version :docker version
  • View details :docker info
  • help docker --help

2、 Mirror command

2.1、 Lists the images on the localhost

  • docker images
    • REPOSITORY: Represents the repository source for the mirror
    • TAG: Mirrored label There can be more than one repository source TAG, Represents different versions of the repository source , We use REPOSITORY:TAG To define different mirrors . If you don't specify a mirror version , You just write ubuntu,docker Use by default ubuntu:latest Mirror image
    • IMAGE ID: Mirror image ID
    • CREATED: Image creation time
    • SIZE: Image size
  • Parameters
    • -a: List all local images ( Contains the intermediate image layer )
    • -q: Image only id
    • --digests: Show only summary information
    • --no-trunc: Displays complete mirror information ( Make a complete list of id)
  • Commonly used
    • docker images -qa
  • docker search Mirror name
  • Parameters
    • --no-trunc: Displays complete mirror information
    • -s: List the images with the number of collections no less than the specified value
    • --automated: List only automated build Type of mirror ( Self built )

2.3、 Pull the specified image

  • docker pull Mirror name :TAG, Don't write TAG Default latest

2.4、 Delete the specified image

  • docker rmi -f Image name or id
  • Commonly used
    • Batch deletion :docker rmi -f Mirror name 1:TAG Mirror name 2:TAG
    • Delete all :docker rmi -f $(docker images -qa)

3、 Container order

3.1、 Create and start the container

  • docker run [options] Mirror image [command] [arg...]
  • Parameters
    • --name=" New container name ": Specify a name for the container , Don't write random distribution
    • -d: Background running container , And return to the container ID, That is, start the daemon container
    • -i: Run container in interactive mode , Usually with -t Use at the same time
    • -t: Reassign a pseudo input terminal to the container , Usually with -i Use at the same time
    • -P: Random port mapping
    • -p: Specify port mapping , There are four formats
      • ip:hostPort:containerPort
      • ip::containerPort
      • hostPort:containerPort
      • containerPort
  • Be careful : If you start a guardian container , There's no front desk ( The terminal is also ) Conduct , Do nothing , It will be automatically shut down as soon as it is started

3.2、 List currently running containers

  • docker ps [option]
  • Parameters
    • -a: Lists all currently running containers + Historically run
    • -l: Displays the most recently created container
    • -n: According to recent n Containers created for example -n 10
    • -q: silent mode , Only the container number is displayed
    • --no-trunc : Untruncated output ( complete id)

3.3、 Exit the container

  • exit: Exit and stop the container
  • ctrl+P+Q: Quit, don't stop quitting ( recommend )

3.4、 Start the container

  • docker start Containers id Or container name

3.5、 Restart container

  • docker restart Containers id Or container name

3.6、 Stop container

  • stop it :docker stop Containers id Or container name
  • Force to stop :docker kill Containers id Or container name

3.7、 Delete stopped

  • Delete one :docker rm Containers id
  • Delete all :docker rm -f $(docker ps -a -q) perhaps docker ps -a -q | xargs docker rm(linux The form of the pipe , The return value of the previous command is used as the input of the next command )

3.8、 Start the daemon container

  • docker run -d Container name ( for example :docker run -d centos) Return a container id
  • then docker ps -a To view the , You will find that the container has exited
    • It's important to point out : Docker Container running in background , There must be a foreground process , The container runs commands that are not suspended ( Like running top,tail), It just exits automatically
    • This is docker Problem of mechanism , Such as your web Containers , We use nginx For example , Under normal circumstances , We configured the startup service to only start the response service that will do . for example service nginx start however , To do so ,nginx Run in background process mode , As a result docker There are no running applications in the foreground , After the container background is started , Would kill himself immediately because he thought he had nothing else to do . therefore , The best solution is , Run the program you want to run as a previous console process

3.9、 View container log

  • docker logs [option] Containers id ( That is, the content displayed by the terminal inside the container ) Press ctrl+c You can quit
  • Parameters
    • -t: It's adding a timestamp
    • -f: Follow the latest log print
    • --tail Numbers : Show how many last
  • For example, running in a container shell Script :docker run -d centos /bin/sh -c "while true;do echo hello zzyy;sleep 2;done"

3.10、 View the processes running inside the container

  • docker top Containers id

3.11、 Look inside the container for details

  • docker inspect Containers id

3.12、 Interact with the container

  • docker attach Containers id
    • Directly enter the container start command terminal , No new processes will be created ( The terminal inside the container ), If you use exit Exit to the host , Will stop the container
  • docker exec -it Containers id shell command ( must )
    • Is to open a new terminal in a container , And you can start a new process , Use exit Exit to the host , The container will not stop
    • for example :docker exec -it Containers id /bin/bash——> Enter the container and open a new terminal
    • for example :docker exec -it Containers id ls——> Returns the list of files entered into the container's default directory ( Take things out of the air : There is no need to enter the container )
    • for example :docker exec -it Containers id ls /tmp——> Return to container tmp List of files in the directory ( Take things out of the air : There is no need to enter the container )

3.13、 Copy files

  • docker cp Containers id: Container path Destination host path

3、 ... and 、 Mirror image principle

1、 Image structure

  • Image is a lightweight 、 Executable standalone package , It is used to package software running environment and software developed based on running environment , It contains everything you need to run a piece of software , Including code 、 Runtime 、 library 、 Environment variables and profiles
  • UnionFS( Federated file system )
    • Union file system (UnionFS) It's a kind of layering 、 Lightweight and high performance file system , It supports changes to the file system as a single commit layer upon layer , At the same time, you can mount different directories to the same virtual file system (unite several directories into a single virtual filesystem).Union The file system is Docker The foundation of the mirror . Images can be inherited by layering , Based on the basic image ( No father image ), Can make a variety of specific application image
    • characteristic : Loading multiple file systems at once , But from the outside it looks like , Only one file system can be seen , Joint loading will stack up all layers of file systems , In this way, the final file system will contain all the underlying files and directories
  • Loading principle
    • docker The image of is actually composed of file systems layer by layer , This level of file system UnionFS
    • bootfs(boot file system) It mainly includes bootloader and kernel, bootloader Mainly boot loading kernel, Linux It will load when it is just started bootfs file system , stay Docker The bottom of the image is bootfs. This floor is typical of Linux/Unix The system is the same , contain boot Loader and kernel . When boot After loading, the whole kernel is in memory , At this time, the right to use memory has been granted by bootfs To the kernel , At this time, the system will also uninstall bootfs
    • rootfs(root file system), stay bootfs above . It contains the typical Linux In the system /dev, /proc, /bin, /etc Etc. standard directories and documents .rootfs Is a variety of different operating system distributions , such as Ubuntu,Centos wait
    • Usually we install it into the virtual machine CentOS There are several G, Why? docker Only here 200M?
      • For a streamlined OS,rootfs It can be very small , Just include the most basic commands 、 Tools and libraries will do , Because the bottom uses Host Of kernel, I just need to provide rootfs That's it . This shows that for different linux Distribution version , bootfs Basically consistent , rootfs There will be differences , So different distributions can be shared bootfs
    • Why? docker Medium tomcat It's big , Hundreds of megabytes ?
      • because tomcat The image also contains other library files that it depends on ,kernel kernel 、centos、jdk8、tomcat, So a mirror is like a miniature linux System , Contains an application running environment , Multi layer file stack , Finally, a mirror file is exposed
      • Download in layers
  • The advantages of layering
    • One of the biggest benefits is - Shared resources
    • such as : There are multiple images from the same base The image is built , Then the host only needs to save one copy on the disk base Mirror image , At the same time, only one copy needs to be loaded in memory base Mirror image , You can serve all containers . And every layer of the image can be shared
  • Structural features
    • docker Images are read-only
    • When the container starts , A new writable layer is loaded on top of the image , This layer is often called the container layer , The container layer is called the image layer

2、docker commit

  • Submit a container to a new container
  • docker commit -m=" Description information submitted " -a=" author " Containers id The target mirror name to create :[TAG] Don't write default latest
  • Case study
    • Pull tomcat8.5.31 Mirror image , Delete after running webapps In the catalog doc Catalog (rm -rf Directory name )( Other versions of tomcat Of webapps Directory is empty , After starting, directly visit the newspaper 404 It's normal )
    • Put the container commit Submit to a new image
    • Run a container with the new image , Click on document Whether it is 404

Four 、 Container data volume

1、 summary

  • Problems encountered
    • Package the application and operation environment to form container operation , Running can be accompanied by a container , Data cannot be persisted , Data cannot be shared between containers
    • The traditional way to persist : adopt docker commit Generate a new image , Make the data a part of the image to be saved
  • Solution
    • Container data volume : It's kind of similar rdb and aof, Data in persistent containers and inheritance between containers + Shared data

2、 Data volume

  • Solve the persistence of data in the container

  • Solution : Save the important data in the container to the host

  • Mode one : Specify the mapping relationship when starting the container

    • command :docker run -it -v / Host directory :/ In-container directory Mirror image /bin/bash (-v: Specify the mapping relationship , There can be multiple , If the directory does not exist , Will create a directory )

    • Check for success :docker inspect Containers id (RW: Represents that the container is readable and writable to the directory ,Source For Host Directory ,Destination For container Directory )

      • "Mounts": [
        {
        "Type": "bind",
        "Source": "/tmp/hosttest",
        "Destination": "/tmp/containertest",
        "Mode": "",
        "RW": true,
        "Propagation": "rprivate"
        }
        ],
    • test

      • test 1: On both sides , See if it works

        • 1. The host writes to the file 
          [root@localhost hosttest]# echo "I'm host" > a.txt
          [root@localhost hosttest]# cat a.txt
          I'm host
          2. Container modify file 
          [root@51037b519837 containertest]# vi a.txt
          [root@51037b519837 containertest]# cat a.txt
          I'm host
          container update
          3. Host view file 
          [root@localhost hosttest]# cat a.txt
          I'm host
          container update
          
          
      • test 2: Closed container , Host modification file , See if it works

        • 1. Closed container 
          [root@localhost hosttest]# docker kill 51037b519837
          51037b519837
          2. Modify the file on the host 
          [root@localhost hosttest]# vim a.txt
          [root@localhost hosttest]# cat a.txt
          I'm host
          container update
          host update
          3. Start the container 
          [root@localhost hosttest]# docker start 51037b519837
          51037b519837
          4. see file 
          [root@localhost hosttest]# docker exec -it 51037b519837 /bin/bash
          [root@51037b519837 /]# cd /tmp/containertest/
          [root@51037b519837 containertest]# cat a.txt
          I'm host
          container update
          host update
          
      • Conclusion : Whether the container is closed or not , Host modification file , The container will be updated after it starts , amount to java Two references in point to the same memory address

    • Commands with authority :docker run -it -v / Host directory :/ In-container directory :ro Mirror image /bin/bash (-v: Specify the mapping relationship , There can be multiple , If the directory does not exist , Will create a directory ;ro: representative read only read-only , The container cannot be modified

      • 1. Create a container 
        [root@localhost hosttest]# docker run -it -v /tmp/hosttestro:/tmp/containertestro:ro --name ctro centos
        [root@9d0eef947060 /]# 
        2. Check for success  rw Has become false
        [root@localhost hosttest]# docker inspect 9d0eef947060
        "Mounts": [
                    {
                        "Type": "bind",
                        "Source": "/tmp/hosttestro",
                        "Destination": "/tmp/containertestro",
                        "Mode": "ro",
                        "RW": false,
                        "Propagation": "rprivate"
                    }
                ],
        3. stay host Create a new file on and write to 
        [root@localhost hosttestro]# echo "I'm read only" > rotest.txt
        [root@localhost hosttestro]# cat rotest.txt
        I'm read only
        4. Enter container modification 
        [root@localhost hosttestro]# docker exec -it 9d0eef947060 /bin/bash
        [root@9d0eef947060 /]# cd tmp/containertestro/
        [root@9d0eef947060 containertestro]# ls
        rotest.txt
        [root@9d0eef947060 containertestro]# vi rotest.txt
        5. Find out vi The file cannot be edited 
        -- INSERT -- W10: Warning: Changing a readonly file
        6. You can't create your own files 
        [root@9d0eef947060 containertestro]# echo "I'm container" > aa.txt
        bash: aa.txt: Read-only file system
        
        
  • Mode two : Use DockerFile Specify when building the image

    • DockerFile Instructions :VOLUME[" Container directory 1"," Container directory 2"," Container directory 3",...]

      • For portability and sharing , use -v Host Directory : The container directory method cannot be used directly in Dockerfile To realize . Because the host directory is dependent on a specific host , There is no guarantee that such a specific directory exists on all hosts
    • establish DockerFile file , And write content

      • [root@localhost mydocker]# vim dockerfile
        [root@localhost mydocker]# cat dockerfile
        # volume test
        
        FROM centos
        
        VOLUME ["/dataVolumeContainer1","/dataVolumeContainer2"]
        
        CMD echo "finished,--------success1"
        
        CMD /bin/bash
        [root@localhost mydocker]#
        
        
    • Command build mirror

      • docker build -f /test/mydocker/dockerfile -t ma/centos:1.0 . (-f: Appoint dockfile File path ;.: The last point cannot be omitted , Specifies the context of the build )

      • [root@localhost mydocker]# docker images
        REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
        ma/centos           1.0                 6c074087077c        37 seconds ago      209MB
        mytomcat            1.0                 ca4cffd1de8f        15 hours ago        463MB
        centos              latest              300e315adb2f        26 hours ago        209MB
        tomcat              8.5.31              df50c9d355cf        2 years ago         463MB
        
        
    • Start the mirror and see where the data volume is on the host

      • [root@localhost mydocker]# docker run -it ma/centos:1.0
        [root@c86811d3480e /]# [root@localhost mydocker]#
        [root@localhost mydocker]# docker inspect c86811d3480e
         "Mounts": [
                    {
                        "Type": "volume",
                        "Name": "bf9c3b442d1f754f6a80c3496a8f251b31e6ae962871c123f8142a253cc1904c",
                        "Source": "/var/lib/docker/volumes/bf9c3b442d1f754f6a80c3496a8f251b31e6ae962871c123f8142a253cc1904c/_data",
                        "Destination": "/dataVolumeContainer1",
                        "Driver": "local",
                        "Mode": "",
                        "RW": true,
                        "Propagation": ""
                    },
                    {
                        "Type": "volume",
                        "Name": "2e26e661586d11af53ab8d322016458e392c2e1aa4d9727d84b11a3da1e03f99",
                        "Source": "/var/lib/docker/volumes/2e26e661586d11af53ab8d322016458e392c2e1aa4d9727d84b11a3da1e03f99/_data",
                        "Destination": "/dataVolumeContainer2",
                        "Driver": "local",
                        "Mode": "",
                        "RW": true,
                        "Propagation": ""
                    }
                ],
        
        
    • Docker Mount the host directory Docker The visit appears cannot open directory .: Permission denied terms of settlement : Add one more... After mounting the directory --privileged=true Parameters can be

3、 Data volume container

  • Named container mounts the data volume , Other containers mount this ( Parent container ) Implement data sharing , A container for mounting data volumes , Call it a data volume container

  • Realization way

    • Start a parent container

      • docker run -it --name dc1 ma/centos:1.0
    • Mount two child containers Use --volumes-from Parameters

      • docker run -it --name dc2 --volumes-from dc1 ma/centos:1.0
      • docker run -it --name dc3 --volumes-from dc1 ma/centos:1.0
    • test

      • stay dc1 Add files to ,dc2,dc3 Also add
      • Delete dc1, modify dc2 In the file ,dc3 Also changed the
      • Delete dc2,dc3 You can still access
      • newly build dc4 Inherit dc3, Delete dc3,dc4 You can still access
    • Transfer of configuration information between containers , The life cycle of a data volume continues until no container USES it

    • The essential reason : The transmission of configuration information

      • 1. establish dc1,dc2、dc3、dc4 Container volume inheritance dc1,dc4 Use the original image , It doesn't contain VOLUME Instructions 
        docker run -it --name dc1 ma/centos:1.0
        docker run -it --name dc2 --volumes-from dc1 ma/centos:1.0
        docker run -it --name dc3 --volumes-from dc1 ma/centos:1.0
        docker run -it --name dc4 --volumes-from dc1 centos (dc4 Use the original image , It doesn't contain VOLUME Instructions )
        2. According to the container id Look at their information 
        [root@localhost _data]# docker inspect dc1
        "Mounts": [
                    {
                        "Type": "volume",
                        "Name": "ce66ad2a242a771b9735717ec305521dfcbad324adbee58bd6dea2795fc1b4f0",
                        "Source": "/var/lib/docker/volumes/ce66ad2a242a771b9735717ec305521dfcbad324adbee58bd6dea2795fc1b4f0/_data",
                        "Destination": "/dataVolumeContainer1",
                        "Driver": "local",
                        "Mode": "",
                        "RW": true,
                        "Propagation": ""
                    },
                    {
                        "Type": "volume",
                        "Name": "160ec2ca48392b73c53c2dbe709d414c81ca6be1dfeb85d70e4f7dc37c3fc892",
                        "Source": "/var/lib/docker/volumes/160ec2ca48392b73c53c2dbe709d414c81ca6be1dfeb85d70e4f7dc37c3fc892/_data",
                        "Destination": "/dataVolumeContainer2",
                        "Driver": "local",
                        "Mode": "",
                        "RW": true,
                        "Propagation": ""
                    }
                ],
        [root@localhost _data]# docker inspect dc2
        "Mounts": [
                    {
                        "Type": "volume",
                        "Name": "160ec2ca48392b73c53c2dbe709d414c81ca6be1dfeb85d70e4f7dc37c3fc892",
                        "Source": "/var/lib/docker/volumes/160ec2ca48392b73c53c2dbe709d414c81ca6be1dfeb85d70e4f7dc37c3fc892/_data",
                        "Destination": "/dataVolumeContainer2",
                        "Driver": "local",
                        "Mode": "",
                        "RW": true,
                        "Propagation": ""
                    },
                    {
                        "Type": "volume",
                        "Name": "ce66ad2a242a771b9735717ec305521dfcbad324adbee58bd6dea2795fc1b4f0",
                        "Source": "/var/lib/docker/volumes/ce66ad2a242a771b9735717ec305521dfcbad324adbee58bd6dea2795fc1b4f0/_data",
                        "Destination": "/dataVolumeContainer1",
                        "Driver": "local",
                        "Mode": "",
                        "RW": true,
                        "Propagation": ""
                    }
                ],
        
        [root@localhost _data]# docker inspect dc3
        "Mounts": [
                    {
                        "Type": "volume",
                        "Name": "ce66ad2a242a771b9735717ec305521dfcbad324adbee58bd6dea2795fc1b4f0",
                        "Source": "/var/lib/docker/volumes/ce66ad2a242a771b9735717ec305521dfcbad324adbee58bd6dea2795fc1b4f0/_data",
                        "Destination": "/dataVolumeContainer1",
                        "Driver": "local",
                        "Mode": "",
                        "RW": true,
                        "Propagation": ""
                    },
                    {
                        "Type": "volume",
                        "Name": "160ec2ca48392b73c53c2dbe709d414c81ca6be1dfeb85d70e4f7dc37c3fc892",
                        "Source": "/var/lib/docker/volumes/160ec2ca48392b73c53c2dbe709d414c81ca6be1dfeb85d70e4f7dc37c3fc892/_data",
                        "Destination": "/dataVolumeContainer2",
                        "Driver": "local",
                        "Mode": "",
                        "RW": true,
                        "Propagation": ""
                    }
                ],
        [root@localhost _data]# docker inspect dc4
        "Mounts": [
                    {
                        "Type": "volume",
                        "Name": "ce66ad2a242a771b9735717ec305521dfcbad324adbee58bd6dea2795fc1b4f0",
                        "Source": "/var/lib/docker/volumes/ce66ad2a242a771b9735717ec305521dfcbad324adbee58bd6dea2795fc1b4f0/_data",
                        "Destination": "/dataVolumeContainer1",
                        "Driver": "local",
                        "Mode": "",
                        "RW": true,
                        "Propagation": ""
                    },
                    {
                        "Type": "volume",
                        "Name": "160ec2ca48392b73c53c2dbe709d414c81ca6be1dfeb85d70e4f7dc37c3fc892",
                        "Source": "/var/lib/docker/volumes/160ec2ca48392b73c53c2dbe709d414c81ca6be1dfeb85d70e4f7dc37c3fc892/_data",
                        "Destination": "/dataVolumeContainer2",
                        "Driver": "local",
                        "Mode": "",
                        "RW": true,
                        "Propagation": ""
                    }
                ],
        
        
      • Find out dc1,dc2,dc3,dc4 The host's container volumes are in the same location , That's why each container is shared , Even if dc4 The image itself does not specify a container volume , The container volume is also inherited from dc1 I inherited it

5、 ... and 、Dockerfile

1、 summary

  • Dockfile Used to build image files , A script consisting of a series of commands and parameters
  • Build three steps
    • To write dockerfile
    • docker build
    • docker run
  • The basic rule
    • Each reserved word instruction is capitalized and followed by at least one parameter
    • Instructions are executed from top to bottom
    • '#' Notation
    • Each instruction creates a new image layer , And submit... To the image
  • Execute the process
    • docker Run a container from the underlying image
    • Execute an instruction to modify the container
    • Execution is similar to docker commit Submit a new image layer
    • docker Then start a new container based on the submitted image
    • perform dockerfile Until all instructions are executed
  • From the perspective of application software ,Dockerfile、Docker The mirror with Docker Containers represent three different phases of software ,
    • Dockerfile It's the raw material of software
      • I need to define a Dockerfile,Dockerfile Defines everything the process needs .Dockerfile It involves executing code or files 、 environment variable 、 Dependency package 、 Runtime environment 、 Dynamic link library 、 Distribution of the operating system 、 Service process and kernel process ( When application processes need to deal with system services and kernel processes , You need to think about how to design namespace Permission control ) wait ;
    • Docker A mirror is a software deliverable
      • In use Dockerfile After defining a file ,docker build There will be a Docker Mirror image , When running Docker Mirror image , Will really start providing services
    • Docker The container can be thought of as the running state of the software
      • Containers are direct service providers
    • Dockerfile Facing the development of ,Docker Mirroring becomes the delivery standard ,Docker Containers involve deployment and operations , All three are indispensable , To act as Docker The cornerstone of the system

2、dockerfile Instructions

  • FROM: Specify base image ,DockerHub in 99% The mirror image of the scratch It's a mirror image
  • MAINTAINER: Specify the author and mailbox for example : The author's name < mailbox >
  • RUN: The command that runs when the container is built
  • EXPOSE: The port where the current container is exposed
  • WORKDIR: After creating the container , The working directory that the terminal logs in by default , A foothold
  • ENV: It is used to set environment variables during the process of building image , for example :ENV MY_PATH /tmp Use in other places $MY_PATH
  • ADD: Unzip the host file , Automatic processing URL and tar
  • COPY: similar ADD, But don't decompress The source path ( In the host )/ The target path ( In container )
  • VOLUME: Specify container data volume
  • CMD: Container start is the command to run
    • dockerfile There can be multiple CMD, But only the last one will take effect , Will be covered , If you specify CMD, The specified CMD
    • Supported format
      • shell Format :CMD < command >
      • exec Format :CMD[" Executable file "," Parameters 1"," Parameters 2"...]
  • ENTRYPOINT: Specify the command and... That the container starts to run CMD It works the same , But it doesn't cover , Will add , If you specify CMD, Append specified CMD It specifies ENTRYPOINT They don't execute CMD
  • ONBUILD: When building an inherited dockfile It's a run command , When the mirror image is build The parent image will be triggered ONBUILD Instructions

3、dockerfile Case study

3.1、 Customize mycentos

  • To write dockerfile

    • #  Specify base image 
      FROM centos
      #  Set up the author email 
      MAINTAINER ms<ms167@126.com>
      #  Set the environment variable 
      ENV MYPATH /use/local
      #  Set the foothold 
      WORKDIR $MYPATH
      #  install vim  and  ifconfig Wait for the order   Multiple RUN  It can be used && The connection creates only one mirror layer , Otherwise, a RUN A mirror layer 
      # RUN yum -y install vim
      # RUN yum -y install net-tools
      RUN yum -y install vim && yum -y install net-tools
      #  The outward exposed port 
      EXPOSE 80
      #  Command to execute when container starts   Only the last one works 
      CMD echo $MYPATH
      CMD echo "success"
      CMD /bin/bash
      
  • according to dockerfile Build a mirror image

    • command :docker build -f dockerfile route -t Mirror name : edition .
      • Be careful :-t Need to be in -f after , It should only be the last parameter
      • -f: Appoint dockerfile route , Do not write default current path search Dockerfile
      • .: The last dot represents the context path
        • Context path , Refer to docker Building a mirror , Sometimes you want to use files on your computer ( Like copying ),docker build When the command knows the path , It will package all the content under the path
        • analysis : because docker The operating mode of is C/S. Our machine is C,docker Engine is S. The actual build process is in docker It's done under the engine , So we can't use our local files at this time . This requires us to package and provide the files under the specified directory of our machine to docker Engine USES
        • If the last parameter is not specified , So the default context path is Dockerfile Where it is
        • Be careful : Do not put useless files in the context path , Because it will be packaged and sent to docker engine , If there are too many files, the process will be slow
    • Error reported during execution Errors during downloading metadata for repository 'appstream': The solution
      • wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-8.repo
      • Clear cache :yum clean all
      • Install new dependencies ( cache ):yum makecache
      • restart docker( Very important ):systemctl restart docker
      • Just rebuild
  • List the change history of the image :docker history Mirror image

3.2、CMD and ENTRYPOINT Command difference

CMD Instructions
  • Specifies the default program to run for the container that is started , End of program running , The container is over ,Dockerfile If there are more than one CMD Instructions , Only the last one takes effect ,CMD The program specified by the instruction can be docker run The command line parameter specifies the program to be run
  • Format
    • CMD <shell command >
    • CMD ["< Executable file or command >"," "," ",...]
    • CMD [" "," ",...] # It is written for ENTRYPOINT The program specified by the instruction provides default parameters
    • The second format is recommended , The implementation process is relatively clear . In fact, the first format will be automatically converted to the second format in the process of running , And the default executable is sh
ENTRYPOINT Instructions
  • To write dockerfile

    • # 1. What is actually carried out is  curl -s https://ip.cn      curl Command to download the web page html -i Parameter download header information 
      FROM centos
      CMD echo "success"
      ENTRYPOINT ["curl","-s","https://ip.cn"]
      #  Even if you carry CMD command   It will still be executed ENTRYPOINT
      
      # 2. What is actually carried out is  curl -s https://ip.cn  And CMD and ENTRYPOINT It's not in the order of 
      FROM centos
      ENTRYPOINT ["curl","-s","https://ip.cn"]
      CMD echo "success"
      
      # 3. What is actually carried out is  curl https://ip.cn  Only ENTRYPOINT The last one in the back CMD To splice to ENTRYPOINT On the order ( There are more than one in the back )  The one in front can't 
      FROM centos
      CMD ["-i"]
      ENTRYPOINT ["curl"]
      CMD ["-s"]
      CMD ["https://ip.cn"]
      #  It's started with CMD command   For example, there are  -i  What is actually carried out is  curl -i  You're going to report a mistake (run  It's also a parameter CMD command )
      
      # 4. What is actually carried out is curl -s https://ip.cn  If there are more than one ENTRYPOINT  Only the last one takes effect 
      FROM centos
      CMD ["-i"]
      ENTRYPOINT ["curl"]
      CMD ["-s"]
      CMD ["https://ip.cn"]
      ENTRYPOINT ["curl","-s","https://ip.cn"]
      #  It's started with CMD command   For example, there are  -i  It'll be stitched together   What is actually carried out is curl -s https://ip.cn -i
      
      # 5. If ENTRYPOINT Not used []  form   There will be no additional   What is actually carried out is curl -s https://ip.cn
      FROM centos
      ENTRYPOINT curl -s https://ip.cn
      CMD ["-i"]
      
  • Be careful : If there is ENTRYPOINT There is , After the container starts, it takes precedence ENTRYPOINT, Not execute CMD, without ENTRYPOINT, The last one will be executed CMD, And CMD and ENTRYPOINT It's not in the order of

4、 Customize tomcat

  • preparation

    • Create... In the directory a.txt( Used for testing COPY)
    • Upload apache-tomcat-8.5.61.tar.gz Go to the directory
    • Upload jdk-8u11-linux-x64.tar.gz Go to the directory
  • To write dockerfile

    • FROM centos
      MAINTAINER ms<ms167@126.com>
      #  Put the current context of the host c.txt Copy to container /usr/local/ Under the path 
      COPY a.txt /usr/local/cincontainer.txt
      #  hold java And tomcat Add to container and unzip   What exactly is the extracted directory like   Want to see tar.gz Inside 
      ADD jdk-8u11-linux-x64.tar.gz /usr/local/
      ADD apache-tomcat-8.5.61.tar.gz /usr/local/
      #  install vim Editor 
      RUN yum -y install vim
      #  Set up the WORKDIR route , Log in to the landing point 
      ENV MYPATH /usr/local
      WORKDIR $MYPATH
      #  To configure java And tomcat environment variable   Specific reference to linux The configuration   The name of the directory to be unzipped   Want to see tar.gz Inside 
      ENV JAVA_HOME /usr/local/jdk1.8.0_11
      ENV CLASSPATH $JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
      ENV CATALINA_HOME /usr/local/apache-tomcat-8.5.61
      ENV CATALINA_BASE /usr/local/apache-tomcat-8.5.61
      ENV PATH $PATH:$JAVA_HOME/bin:$CATALINA_HOME/lib:$CATALINA_HOME/bin
      # Port on which the container listens at runtime 
      EXPOSE  8080
      #  Run on startup tomcat
      # ENTRYPOINT ["/usr/local/apache-tomcat-9.0.8/bin/startup.sh" ]
      # CMD ["/usr/local/apache-tomcat-9.0.8/bin/catalina.sh","run"]
      CMD /usr/local/apache-tomcat-8.5.61/bin/startup.sh && tail -F /usr/local/apache-tomcat-8.5.61/logs/catalina.out
       
      
  • Build a mirror image

    • docker build -f /test/mydocker/mytomcat8/Dockerfile -t mytomcat8:1.0 .
  • Start the container and create the data volume --privileged=true solve Docker Mount the host directory Docker The visit appears cannot open directory .: Permission denied

    • docker run -it -P -v /test/mydocker/mytomcat8/tomcatwebapps:/usr/local/apache-tomcat-8.5.61/webapps -v /test/mydocker/mytomcat8/tomcatlog:/usr/local/apache-tomcat-8.5.61/logs --privileged=true mytomcat8:1.0
  • Through the data volume, you can modify the container in the host tomcat The content in

5、ONBUILD Instructions

  • ONBUILD Instructions are used for sub images to be build when , The parent image triggers

  • To write Dockerfile And build a mirror to run

    • # 1. Parent image 
      FROM centos
      ONBUILD RUN echo "I'm parent-image"
      # docker build -f /test/mydocker/parent-children/parentfile -t parent-image .
      # 2. Sub image 
      FROM parent-image
      CMD echo "I'm child-image"
      # docker build -f /test/mydocker/parent-children/childfile -t child-image .
      
  • See the results when building the child image

    • [root@localhost parent-children]# docker build -f /test/mydocker/parent-children/childfile -t child-image .
      Sending build context to Docker daemon  3.072kB
      Step 1/2 : FROM parent-image
      
       This shows that a trigger was executed   That is, in the parent mirror image ONBUILD Instructions 
      # Executing 1 build trigger
       ---> Running in 49d2db5530c2
      I'm parent-image
      
      Removing intermediate container 49d2db5530c2
       ---> 184b598876a3
      Step 2/2 : CMD echo "I'm child-image"
       ---> Running in 6b6359d232c3
      Removing intermediate container 6b6359d232c3
       ---> ca71e2df6c07
      Successfully built ca71e2df6c07
      Successfully tagged child-image:latest
      

6、 ... and 、 Installation of commonly used software

  • docker Software installation process
    • Search mirroring
    • Pull the mirror image
    • Look at the mirror image
    • Start the container
    • Stop container
    • Remove the container

1、 install tomcat

  • It's already installed , Omit here

2、 install mysql

  • Pull mysql5.7.20 Mirror image
  • Start the container
    • docker run -p 12345:3306 --name mysql -v /test/mysql/conf:/etc/mysql/mysql.conf.d -v /test/mysql/logs:/logs -v /test/mysql/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=123456 -d mysql:5.7.20
    • Command specification :
      • -p 12345:3306: Will host the 12345 Port maps to docker Container of 3306 port .
      • --name mysql: The name of the running container
      • -v /test/mysql/conf:/etc/mysql/mysql.conf.d : Put the host /test/mysql/conf The directory is attached to the container's /etc/mysql/conf.d perhaps mysql.conf.d( The two directories vary according to the version , Inside mysqld.cnf by mysql Configuration file for )
      • -v /test/mysql/logs:/logs: Put the host /test/mysql In the catalog logs The directory is attached to the container's /logs.
      • -v /test/mysql/data:/var/lib/mysql : Put the host /test/mysql In the catalog data The directory is attached to the container's /var/lib/mysql That is to say mysql Of data Catalog
      • -e MYSQL_ROOT_PASSWORD=123456: initialization root User's password .
      • -d mysql:5.7.20 : Background program running mysql:5.7.20
  • Just connect outside the container

3、 install redis

  • Pull redis3.2 Mirror image
  • Write the configuration file and put it in the directory you created ( The corresponding data volume is required when starting )
    • In this directory /test/redis/conf Create redis.conf
    • Write the content of the configuration file on the official website to , take bind Comment out
    • stay docker Start in redis Must put :daemonize Set to no, This is very important , If not no docker Will always fail to start , as a result of docker It needs to run in the background , This configuration option is also started as a daemon , The two conflict
      • It's OK without setting
  • Start the container
    • docker run -p 6379:6379 -v /test/redis/data:/data -v /test/redis/conf:/usr/local/etc/redis/conf -d redis:3.2 redis-server /usr/local/etc/redis/conf --appendonly yes
    • Command specification
      • -v /test/redis/data:/data : Where persistent files are stored
      • -v /test/redis/conf:/usr/local/etc/redis/conf : Where configuration files are stored
      • redis-server /usr/local/etc/redis/conf : Specify profile startup
      • --appendonly yes : Turn on persistence
  • Just connect outside the container

7、 ... and 、 Push the image to alicloud

  • Push pull process

  • Create a warehouse in alicloud image warehouse

    • The following specific address can be viewed in alicloud image warehouse
  • stay linux Log in to alicloud image warehouse

    • sudo docker login --username=xxxxxx registry.cn-hangzhou.aliyuncs.com
  • stay linux Push image to warehouse

    • sudo docker tag [ImageId] Warehouse address :[ Image version number ]
    • sudo docker push Warehouse address :[ Image version number ]
    • Be careful : these two items. [ Image version number ] Be consistent
  • After the push is successful, it can be pulled to the local area

    • sudo docker pull Warehouse address :[ Image version number ]

版权声明
本文为[xiaokantianse]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224113750144P.html

Scroll to Top