Docker introduction practical learning summary
1, Docker overview
The learning experience of this article is summarized in the famous UP Master of station B > > crazy God says Java:https://space.bilibili.com/95256449/
1. Why did Docker appear?
One product: development – online two environments! Application environment, application configuration!
Development - operation and maintenance. Question: I can allow it on my computer! The service is unavailable due to version update! Is it a big test for operation and maintenance?
The environment configuration is very troublesome, and everyone has to deploy the environment (cluster Redis, ES, Hadoop...)! It takes a lot of trouble.
Release a project (jar + (Redis MySQL JDK ES)). Can the project be installed and packaged with the environment!
Previously, configuring an application environment Redis MySQL JDK ES Hadoop on the server is too cumbersome to be cross platform.
Development environment Windows, finally released to Linux!
Tradition: develop jar s and do it through operation and maintenance!
Now: development, packaging, deployment and launch, and a set of processes is completed!
Android process: java apk publish (app store) one three use apk one installation is available!
Docker process: Java jar (environment) - package project with environment (image) - (docker warehouse: store)-----
Docker proposed solutions to the above problems!
Docker's idea comes from containers!
JRE - multiple applications (Port conflict) - originally, they are all cross!
Isolation: the core idea of Docker! Pack and pack! Each box is isolated from each other.
Docker can make full use of the server through the isolation mechanism!
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-4Lfi97oy-1657791393461)(E:\Typora image save location \83.jpg)]
2. Docker's history
In 2010, several young people set up a company dotcloud in the United States
Do some pass cloud computing services! LXC (Linux Container) related container technology!
Linux Container is a kernel virtualization technology that can provide lightweight virtualization to isolate processes and resources.
They named their technology (containerization Technology) Docker
Docker didn't attract the attention of the industry when it was just born! dotCloud, you can't live!
In 2013, Docker was open source!
More and more people find the advantages of docker! Fire. Docker will be updated every month!
Docker1.0 was released on April 9, 2014!
Why is docker so popular? Very light!
Before container technology came out, we all used virtual machine technology!
Virtual machine: install a VMware in the window. Through this software, we can virtualize one or more computers! Bulky!
Virtual machine also belongs to virtualization technology. Docker container technology is also a kind of virtualization technology!
The difference between the two:
VMware: Linux CentOS native image (one computer!) Isolation, need to start multiple virtual machines! A few G a few minutes
docker: isolation, image (the core environment 4m + jdk + mysql) is very small, just run the image! Small! A few M seconds to start!
3. Talk about Docker
Docker is developed based on Go language! Open source project!
Docker official website: https://www.docker.com/
Documentation: https://docs.docker.com/ Docker's documents are super detailed!
Warehouse: https://hub.docker.com/
4. What can Docker do
Previous virtual machine technology
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-5LHk29gc-1657791393462)(E:\Typora image save location \51.jpg)]
Disadvantages of virtual machine technology:
1. A lot of resources are occupied
2. Redundant steps
3. Slow startup!
Container technology
Containerization technology does not simulate a complete operating system
Compare Docker and virtual machine technologies:
Traditional virtual machine virtualizes a piece of hardware, runs a complete operating system, and then installs and runs software on this system.
The applications in the container run directly on the content of the host computer. The container does not have its own kernel or virtual hardware, so it is portable.
Each container is isolated from each other, and each container has its own file system, which does not affect each other.
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-2eGiH7j0-1657791393462)(E:\Typora image save location \52.jpg)]
Devops (development, operation and maintenance)
Faster delivery and deployment of applications
Traditional: a pair of help documents, installer.
Docker: the packaging image release test runs with one click.
More convenient upgrade and capacity expansion
After using Docker, our application deployment is like building blocks
The project is packaged as an image to expand server A! Server B
Simpler system operation and maintenance
After containerization, our development and testing environments are highly consistent
More efficient utilization of computing resources
Docker is a kernel level virtualization, which can run many container instances on a physical machine! The performance of the server can be squeezed to the extreme.
2, Basic composition of Docker
5. Docker structure
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-AYn2Oj3d-1657791393463)(E:\Typora image save location \53.jpg)]
Image:
The docker image is like a target through which container services can be created. The tomcat image = = > Run = = > container (providing server). Through this image, multiple containers can be created (the final service or project run is in the container).
Container:
Docker uses container technology to run an application or a group of applications independently, which is created through image
Start, stop, delete, basic commands
At present, this container can be understood as a simple Linux system.
Repository:
The warehouse is where the image is stored!
Warehouses are divided into public warehouses and private warehouses. (very similar to git)
Docker Hub is foreign.
Alibaba cloud... All have container servers (configure image acceleration!)
3, Docker installation
6. Environmental preparation
1.Linux requires kernel above 3.0
2.CentOS 7
[root@iuwza-an ~/] uname -a #Requirements above 3.0 Linux iuwza-an 3.10.0-1160.59.1.el7.x86_64 #1 SMP Wed Feb 23 16:47:03 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux [root@iuwza-an ~/] cat /etc/os-release #View system version information NAME="CentOS Linux" VERSION="7 (Core)" ID="centos" ID_LIKE="rhel fedora" VERSION_ID="7" PRETTY_NAME="CentOS Linux 7 (Core)" ANSI_COLOR="0;31" CPE_NAME="cpe:/o:centos:centos:7" HOME_URL="https://www.centos.org/" BUG_REPORT_URL="https://bugs.centos.org/" CENTOS_MANTISBT_PROJECT="CentOS-7" CENTOS_MANTISBT_PROJECT_VERSION="7" REDHAT_SUPPORT_PRODUCT="centos" REDHAT_SUPPORT_PRODUCT_VERSION="7"
7. Install docker
Help documentation: https://docs.docker.com/engine/install/
Uninstall and install
#1. Uninstall the old version yum remove docker \ docker-client \ docker-client-latest \ docker-common \ docker-latest \ docker-latest-logrotate \ docker-logrotate \ docker-engine #2. Required installation package yum install -y yum-utils #3. Set the warehouse of the image yum-config-manager \ --add-repo \ https://download.docker.com/linux/centos/docker-ce.repo #The above methods are from abroad by default and are not recommended #Domestic ones are recommended yum-config-manager \ --add-repo \ https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo #Update yum package index yum makecache fast #4. Install docker CE community version related to docker, while ee is enterprise version yum install docker-ce docker-ce-cli containerd.io # Here we can use the community version #5. Start docker systemctl start docker #6. Use docker version to check whether it is successful [root@iuwza-an ~/] docker version Client: Docker Engine - Community Version: 20.10.14 API version: 1.41 Go version: go1.16.15 Git commit: a224086 Built: Thu Mar 24 01:49:57 2022 OS/Arch: linux/amd64 Context: default Experimental: true Server: Docker Engine - Community Engine: Version: 20.10.14 API version: 1.41 (minimum version 1.12) Go version: go1.16.15 Git commit: 87a90dc Built: Thu Mar 24 01:48:24 2022 OS/Arch: linux/amd64 Experimental: false containerd: Version: 1.5.11 GitCommit: 3df54a852345ae127d1fa3092b95168e4a88e2f8 runc: Version: 1.0.3 GitCommit: v1.0.3-0-gf46b6ba docker-init: Version: 0.19.0 GitCommit: de40ad0 #7. Testing [root@iuwza-an ~/] docker pull hello-world Using default tag: latest latest: Pulling from library/hello-world 2db29710123e: Pull complete Digest: sha256:80f31da1ac7b312ba29d65080fddf797dd76acfb870e677f390d5acba9741b17 Status: Downloaded newer image for hello-world:latest docker.io/library/hello-world:latest [root@iuwza-an ~/]# [root@iuwza-an ~/]# [root@iuwza-an ~/] docker run hello-world Hello from Docker! This message shows that your installation appears to be working correctly. [root@iuwza-an ~/] docker images hello-world latest feb5d9fea6a5 8 months ago 13.3kB #8. Uninstall docker #1. Uninstall dependencies yum remove docker-ce docker-ce-cli containerd.io #2. Delete resources rm -rf /var/lib/docker # /var/lib/docker is the default working path of docker!
8. Add Alibaba cloud image acceleration
Log in to Alibaba cloud and find the container image acceleration service
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-fruabbyon-1657791393463) (e:\typora image save location \1.png)]
Click management console
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-781D7psa-1657791393464)(E:\Typora image save location \2.png)]
Find the image accelerator
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG ppkrxdqx-1657791393464) (e:\typora image save location \3.png)]
Configure acceleration file
#1. Create a directory sudo mkdir -p /etc/docker #2. Write configuration file sudo tee /etc/docker/daemon.json <<-'EOF' { "registry-mirrors": ["https://g0y3u1zj.mirror.aliyuncs.com"] } EOF #3. Restart the service sudo systemctl daemon-reload sudo systemctl restart docker
9. Talk about docker run process in detail
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-NXQhOpat-1657791393464)(E:\Typora image save location \54.jpg)]
docker run flowchart
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ZXDZGCtg-1657791393465)(E:\Typora image save location \55.jpg)]
10. Docker underlying principle
How does Docker work?
Docker is a client server system. The daemon of docker runs on the host and is accessed from the client through Socket!
Docker server will execute this command after receiving the docker client instruction!
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG dopdlmsz-1657791393465) (e:\typora image save location \56.jpg)]
Why is Docker faster than VM?
1. Docker has fewer abstraction layers than virtual machines. Because docker does not need Hypervisor to realize hardware resource virtualization, the programs running on the docker container directly use the hardware resources of the actual physical machine. Therefore, docker will have obvious advantages in efficiency in terms of CPU and memory utilization.
2. docker uses the kernel of the host instead of Guest OS.
GuestOS: system (OS) in VM (virtual machine)
HostOS: System in physical machine (OS)
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-WUaatYAk-1657791393466)(E:\Typora image save location \57.jpg)]
Therefore, when creating a new container, docker does not need to reload an operating system kernel like the virtual machine. Still avoid the time-consuming and resource-consuming process of booting and loading the operating system kernel. When creating a new virtual machine, the virtual machine software needs to load GuestOS, and the process of creating a new one is minute level. Because docker directly uses the operating system of the host, this complex process is omitted. Therefore, it only takes a few seconds to create a docker container.
4, Common commands of Docker
11. Help command
docker version #Display the version information of docker. docker info #Display the system information of docker, including the number of images and containers docker command --help #Help command
Address of help document: https://docs.docker.com/engine/reference/commandline/build/
12. Mirror command
docker images #To view the images on all local hosts, you can use docker ls image instead [root@iuwza-an ~/] docker images REPOSITORY TAG IMAGE ID CREATED SIZE mysql latest b2500a44757f 3 days ago 524MB nginx latest fa5269854a5e 5 weeks ago 142MB rubyangxg/jd-qinglong latest 20f5fed7a786 5 weeks ago 787MB hello-world latest feb5d9fea6a5 8 months ago 13.3kB # explain REPOSITORY Mirrored warehouse source TAG Mirror label IMAGE ID image ID CREATED Creation time of image SIZE Size of image # Optional Options: -a, --all # List all mirrors -q, --quiet # Show only image ID docker search #Search image [root@iuwza-an ~/] docker search mysql NAME DESCRIPTION STARS OFFICIAL AUTOMATED mysql MySQL is a widely used, open-source relation... 12652 [OK] mariadb MariaDB Server is a high performing open sou... 4856 [OK] # Optional, filter by searching --filter=STARS=3000 # The search results are STARS greater than 3000 [root@iuwza-an ~/] docker search mysql --filter=STARS=3000 NAME DESCRIPTION STARS OFFICIAL AUTOMATED mysql MySQL is a widely used, open-source relation... 12652 [OK] mariadb MariaDB Server is a high performing open sou... 4856 [OK] docker pull #Download Image docker pull image # Download Image docker pull image name [: tag] [root@iuwza-an ~/] docker pull tomcat Using default tag: latest # If you do not write a tag, the default is latest latest: Pulling from library/tomcat 67e8aa6c8bbc: Pull complete #Layered download, the core federated file system of docker images 627e6c1e1055: Pull complete 0670968926f6: Pull complete 5a8b0e20be4b: Pull complete 7a93fb438607: Pull complete 400f1e54bef0: Pull complete f0b65b53f1a4: Pull complete dc9d1a029c69: Pull complete 42a9874765c5: Pull complete 52140cf8a5cf: Pull complete Digest: sha256:fe703c02e16ea7d3e8d7bdf5a0c03957f2d4a313cfa9ae44878a3ad12e633ccf #autograph Status: Downloaded newer image for tomcat:latest docker.io/library/tomcat:latest #Real address # Equivalent to it docker pull tomcat docker.io/library/tomcat:latest # Specified version download [root@iuwza-an ~/] docker pull mysql:5.6 5.6: Pulling from library/mysql 35b2232c987e: Pull complete fc55c00e48f2: Pull complete 0030405130e3: Pull complete e1fef7f6a8d1: Pull complete 1c76272398bb: Pull complete f57e698171b6: Pull complete f5b825b269c0: Pull complete docker rmi #Delete image docker RMI image [root@iuwza-an ~/] docker rmi -f container ID .... # Delete the specified image or multiple images Untagged: mysql:5.6 Untagged: mysql@sha256:20575ecebe6216036d25dab5903808211f1e9ba63dc7825ac20cb975e34cfcae Deleted: sha256:dd3b2a5dcb48ff61113592ed5ddd762581be4387c7bc552375a2159422aa6bf5 Deleted: sha256:8c5e3b50c7085016b7c692611fdedacba442aa0f4ccf8739f4ecf4d5e49b7d91 Deleted: sha256:2ff31bb829f16adc374868d9ef59254f394816aadfeb6b45da5bec5dcde45540 Deleted: sha256:91bcc75c6967ec46f3f19fa96f248ab3a23589788f9e2c4a1a2e032112def863 Deleted: sha256:127296d2ee30c8716069dc23d015d9ecaa1544d0a2c44712db128ae6a9cb1431 Deleted: sha256:fe36f45d1760f56c23a9957254682d74aa6e7fba931dc8f11addf75684b1aa69 Deleted: sha256:8d6550c8cb1e10f9d0cf1ee3061ecef9e2cb333cdfbf58a02ee27cf2dd5fc35a [root@iuwza-an ~/]# docker rmi -f $(docker images -qa) # Delete all mirrors Untagged: mysql:latest Untagged: mysql@sha256:dc3cdcf3025c3257e8047bb0eaee9d5a42d9f694f84fc5e7b6d12710ba7f6fcb Deleted: sha256:b2500a44757fb9f9eef2089840ea3d7f1f53f36000e500853904786a291a7093 Deleted: sha256:cdd29f3cfa1d360dc591dfa7d97df34097aec9b0a10c5a97b639c1ac2f6229d0 Deleted: sha256:cdb4b319e813cff76042a326e164c92cda2706e546b1e5bcc8def89a7a112675 Deleted: sha256:823dda8b24627ebb50c789527c36964c16914ff1061422eca9bc494be1166a96 Deleted: sha256:ac856325eabcbafe6cefe589df92498eeacf1f741a283faedd9603ed01cc27e1 # Export an image docker save redis:5.0.9-alpine3.11 > /opt/redis.tar.gz # Import an image (delete the corresponding image before importing) docker rmiredis:5.0.9-alpine3.11 docker load < /opt/redis.tar.gz
13. Container command
Note: we can create containers only when we have images. Linux, Download centos images to learn
Image download
#Download centos from docker docker pull centos #Run container operation docker run [Optional parameters] images #Create a new container and start it # Parameter description --name="Name" Container name tomcat01 tomcat02 ,To distinguish containers -d Run in background mode -it Use interactive operation to enter the container to view the content -p Specify the port of the container -p 3306:3306 -p ip:Host port:Container port -p Host port:Container port (Commonly used) -p Container port -P Randomly assigned port # test [root@iuwza-an ~/] docker run -it centos /bin/bash [root@a11f532490e0 /]# ls bin dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var [root@a11f532490e0 /]# exit # Stop and exit the container directly exit [root@iuwza-an ~/]# Ctrl + P Q #Container does not stop exiting docker ps List all running containers docker container list # Optional -a #List currently running containers + bring out historically running containers [root@iuwza-an ~/] docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES [root@iuwza-an ~/]# [root@iuwza-an ~/]# [root@iuwza-an ~/]# [root@iuwza-an ~/] docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES a11f532490e0 centos "/bin/bash" 7 minutes ago Exited (0) 5 minutes ago confident_sinoussi 029e92256e48 feb5d9fea6a5 "/hello" 2 hours ago Exited (0) 2 hours ago charming_jackson #Delete container operation docker rm container id #Delete the specified container. You cannot delete the running container. If you want to forcibly delete rm -f docker rm -f $(docker ps -qa) #Delete all containers docker ps -qa|xargs docker rm #Delete all containers #Start and stop container operation docker start container id #Start container docker restart container id #Restart container docker stop container id #Stop the currently running container docker kill container id #Force the current container to stop
14. Common other commands
Background start container
# Command docker run -d image name [root@iuwza-an ~/] docker run -d centos #Problem: docker ps found that centos stopped #Common pitfalls: when docker container runs in the background, there must be a foreground process. Docker will stop immediately if it finds no application #nginx, after the container is started, it will stop immediately if it finds that it does not provide services , There is no procedure
view log
docker logs -tf --tail Number of containers ID ,No log # Write a shell script [root@iuwza-an ~/] docker run -d centos /bin/bash -c "while true;do echo lijunan;sleep 1;done" [root@iuwza-an ~/]# docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES a0e7e319635f centos "/bin/bash -c 'while..." 15 seconds ago Up 14 seconds nostalgic_perlman # Next, you can display the log [root@iuwza-an ~/] docker logs -tf --tail 10 a0e7e319635f 2022-05-27T09:09:14.745458752Z lijunan 2022-05-27T09:09:15.748032791Z lijunan 2022-05-27T09:09:16.751145691Z lijunan 2022-05-27T09:09:17.754073520Z lijunan 2022-05-27T09:09:18.757048627Z lijunan 2022-05-27T09:09:19.760013732Z lijunan 2022-05-27T09:09:20.763182274Z lijunan 2022-05-27T09:09:21.766216240Z lijunan 2022-05-27T09:09:22.769208712Z lijunan # Show log -tf # Show log -tail number # Number of log entries to display
View the processes in the container
# Command docker top container ID [root@iuwza-an ~/]# docker top a0e7e319635f UID PID PPID C STIME TTY TIME CMD root 27545 27524 0 17:06 ? 00:00:00 /bin/bash -c while true;do echo lijunan;sleep 1;done root 28982 27545 0 17:15 ? 00:00:00 /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 1
View the metadata of the image
# Command docker inspect Container ID #test [root@iuwza-an ~/]# docker inspect a0e7e319635f [ { "Id": "a0e7e319635f6d9a4ac26dc64a20d1d91b03a1eb07abc676d4fd56d05c812388", "Created": "2022-05-27T09:06:07.713427232Z", "Path": "/bin/bash", "Args": [ "-c", "while true;do echo lijunan;sleep 1;done" ], "State": { "Status": "running", "Running": true, "Paused": false, "Restarting": false, "OOMKilled": false, "Dead": false, "Pid": 27545, "ExitCode": 0, "Error": "", "StartedAt": "2022-05-27T09:06:08.171909645Z", "FinishedAt": "0001-01-01T00:00:00Z" }, "Image": "sha256:5d0da3dc976460b72c77d94c8a1ad043720b0416bfc16c52c45d4847e53fadb6", "ResolvConfPath": "/var/lib/docker/containers/a0e7e319635f6d9a4ac26dc64a20d1d91b03a1eb07abc676d4fd56d05c812388/resolv.conf", "HostnamePath": "/var/lib/docker/containers/a0e7e319635f6d9a4ac26dc64a20d1d91b03a1eb07abc676d4fd56d05c812388/hostname", "HostsPath": "/var/lib/docker/containers/a0e7e319635f6d9a4ac26dc64a20d1d91b03a1eb07abc676d4fd56d05c812388/hosts", "LogPath": "/var/lib/docker/containers/a0e7e319635f6d9a4ac26dc64a20d1d91b03a1eb07abc676d4fd56d05c812388/a0e7e319635f6d9a4ac26dc64a20d1d91b03a1eb07abc676d4fd56d05c812388-json.log", "Name": "/nostalgic_perlman", "RestartCount": 0, "Driver": "overlay2", "Platform": "linux", "MountLabel": "", "ProcessLabel": "", "AppArmorProfile": "", "ExecIDs": null, "HostConfig": { "Binds": null, "ContainerIDFile": "", "LogConfig": { "Type": "json-file", "Config": {} }, "NetworkMode": "default", "PortBindings": {}, "RestartPolicy": { "Name": "no", "MaximumRetryCount": 0 }, "AutoRemove": false, "VolumeDriver": "", "VolumesFrom": null, "CapAdd": null, "CapDrop": null, "CgroupnsMode": "host", "Dns": [], "DnsOptions": [], "DnsSearch": [], "ExtraHosts": null, "GroupAdd": null, "IpcMode": "private", "Cgroup": "", "Links": null, "OomScoreAdj": 0, "PidMode": "", "Privileged": false, "PublishAllPorts": false, "ReadonlyRootfs": false, "SecurityOpt": null, "UTSMode": "", "UsernsMode": "", "ShmSize": 67108864, "Runtime": "runc", "ConsoleSize": [ 0, 0 ], "Isolation": "", "CpuShares": 0, "Memory": 0, "NanoCpus": 0, "CgroupParent": "", "BlkioWeight": 0, "BlkioWeightDevice": [], "BlkioDeviceReadBps": null, "BlkioDeviceWriteBps": null, "BlkioDeviceReadIOps": null, "BlkioDeviceWriteIOps": null, "CpuPeriod": 0, "CpuQuota": 0, "CpuRealtimePeriod": 0, "CpuRealtimeRuntime": 0, "CpusetCpus": "", "CpusetMems": "", "Devices": [], "DeviceCgroupRules": null, "DeviceRequests": null, "KernelMemory": 0, "KernelMemoryTCP": 0, "MemoryReservation": 0, "MemorySwap": 0, "MemorySwappiness": null, "OomKillDisable": false, "PidsLimit": null, "Ulimits": null, "CpuCount": 0, "CpuPercent": 0, "IOMaximumIOps": 0, "IOMaximumBandwidth": 0, "MaskedPaths": [ "/proc/asound", "/proc/acpi", "/proc/kcore", "/proc/keys", "/proc/latency_stats", "/proc/timer_list", "/proc/timer_stats", "/proc/sched_debug", "/proc/scsi", "/sys/firmware" ], "ReadonlyPaths": [ "/proc/bus", "/proc/fs", "/proc/irq", "/proc/sys", "/proc/sysrq-trigger" ] }, "GraphDriver": { "Data": { "LowerDir": "/var/lib/docker/overlay2/0a9b9f0c5aad5d8a0e89e7353faa0d2dddaffc96a5fd19bbcd2c6f3924f080fd-init/diff:/var/lib/docker/overlay2/9a0612f9b3394639a52425339816d2764a5415b2eef222d52493f563d9c77742/diff", "MergedDir": "/var/lib/docker/overlay2/0a9b9f0c5aad5d8a0e89e7353faa0d2dddaffc96a5fd19bbcd2c6f3924f080fd/merged", "UpperDir": "/var/lib/docker/overlay2/0a9b9f0c5aad5d8a0e89e7353faa0d2dddaffc96a5fd19bbcd2c6f3924f080fd/diff", "WorkDir": "/var/lib/docker/overlay2/0a9b9f0c5aad5d8a0e89e7353faa0d2dddaffc96a5fd19bbcd2c6f3924f080fd/work" }, "Name": "overlay2" }, "Mounts": [], "Config": { "Hostname": "a0e7e319635f", "Domainname": "", "User": "", "AttachStdin": false, "AttachStdout": false, "AttachStderr": false, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ], "Cmd": [ "/bin/bash", "-c", "while true;do echo lijunan;sleep 1;done" ], "Image": "centos", "Volumes": null, "WorkingDir": "", "Entrypoint": null, "OnBuild": null, "Labels": { "org.label-schema.build-date": "20210915", "org.label-schema.license": "GPLv2", "org.label-schema.name": "CentOS Base Image", "org.label-schema.schema-version": "1.0", "org.label-schema.vendor": "CentOS" } }, "NetworkSettings": { "Bridge": "", "SandboxID": "2780909ae0e6c337c33e7434f145f1f47d1da571ab2189f53b46b5597ab3ca27", "HairpinMode": false, "LinkLocalIPv6Address": "", "LinkLocalIPv6PrefixLen": 0, "Ports": {}, "SandboxKey": "/var/run/docker/netns/2780909ae0e6", "SecondaryIPAddresses": null, "SecondaryIPv6Addresses": null, "EndpointID": "e046f02b5df26d8c33357430c4a9c8ce4d26ce31b441d97d184cc62b4983d61d", "Gateway": "172.17.0.1", "GlobalIPv6Address": "", "GlobalIPv6PrefixLen": 0, "IPAddress": "172.17.0.2", "IPPrefixLen": 16, "IPv6Gateway": "", "MacAddress": "02:42:ac:11:00:02", "Networks": { "bridge": { "IPAMConfig": null, "Links": null, "Aliases": null, "NetworkID": "9ff5166c52695ee57f376032b19cf768b4b079f3577f2e11de5fd1e87747a255", "EndpointID": "e046f02b5df26d8c33357430c4a9c8ce4d26ce31b441d97d184cc62b4983d61d", "Gateway": "172.17.0.1", "IPAddress": "172.17.0.2", "IPPrefixLen": 16, "IPv6Gateway": "", "GlobalIPv6Address": "", "GlobalIPv6PrefixLen": 0, "MacAddress": "02:42:ac:11:00:02", "DriverOpts": null } } } } ]
Enter the currently running container
#We usually use the background mode to run the container. We need to enter the container and modify some configurations #command docker exec -it container id bashshell #test [root@iuwza-an ~/] docker exec -it a0e7e319635f /bin/bash [root@a0e7e319635f /]# [root@a0e7e319635f /]# [root@a0e7e319635f /]# [root@a0e7e319635f /] ps -ef UID PID PPID C STIME TTY TIME CMD root 1 0 0 09:06 ? 00:00:12 /bin/bash -c while true;do echo lijunan;sleep 1;done root 3184 0 0 19:01 pts/0 00:00:00 /bin/bash root 3213 1 0 19:02 ? 00:00:00 /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 1 root 3214 3184 0 19:02 pts/0 00:00:00 ps -ef #Mode II docker attach container ID #test [root@iuwza-an ~/] docker attach a0e7e319635f Executing current code.... # docker exec #After entering the container, open a new terminal, which can be operated inside (commonly used) # docker attach #Entering the terminal where the container is executing will not start a new process
Copy files from the container to the host
docker cp container ID: Path in container Destination host path # View the current host directory [root@iuwza-an ~/] ls /opt/ avalokita bcm-agent bsm-agent containerd hosteye rh [root@iuwza-an /opt/] docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 41347f0574df centos "/bin/bash" About a minute ago Up About a minute competent_kepler # Enter the docker container [root@iuwza-an /opt/] docker attach 41347f0574df [root@41347f0574df /] cd /opt/ [root@41347f0574df opt] ls #Create a new test file in the container [root@41347f0574df opt] touch lijunan.sh [root@41347f0574df opt] ls lijunan.sh [root@41347f0574df opt] exit exit [root@iuwza-an /opt/]# [root@iuwza-an /opt/] docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES [root@iuwza-an /opt/] docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 41347f0574df centos "/bin/bash" 4 minutes ago Exited (0) 16 seconds ago competent_kepler #Copy files to the host [root@iuwza-an /opt/] docker cp 41347f0574df:/opt/lijunan.sh /opt/ [root@iuwza-an /opt/] ls avalokita bcm-agent bsm-agent containerd hosteye lijunan.sh rh #Copying is only a manual process. In the future, we can use -v volume technology to achieve
Learning method: type all my notes and take notes by myself!
5, Summary
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG tkojylhq-1657791393466) (e:\typora image save location \58.jpg)]
15. Encyclopedia of orders
attach Attach local standard input, output, and error streams to a running container #Image of the specified operation of the attach connection under the current shell build Build an image from a Dockerfile # Customize the image through Dockerfile commit Create a new image from a container's changes #Commit the current container as a new image cp Copy files/folders between a container and the local filesystem #Copy files create Create a new container #Create a new container diff Inspect changes to files or directories on a container's filesystem #View the changes of docker container events Get real time events from the server # Get container real time from service exec Run a command in a running container # Running commands on a running container export Export a container's filesystem as a tar archive #Export the container file system as a tar archive [corresponding to import] history Show the history of an image # Show the history of image formation images List images #List the current image of the system import Import the contents from a tarball to create a filesystem image #Import content from the tar package to create a file system image info Display system-wide information # Display system wide information inspect Return low-level information on Docker objects #View container details kill Kill one or more running containers # kill specify docker container load Load an image from a tar archive or STDIN #Load an image from a tar package or standard input [corresponding to save] login Log in to a Docker registry # logout Log out from a Docker registry logs Fetch the logs of a container pause Pause all processes within one or more containers port List port mappings or a specific mapping for the container ps List containers pull Pull an image or a repository from a registry push Push an image or a repository to a registry rename Rename a container restart Restart one or more containers rm Remove one or more containers rmi Remove one or more images run Run a command in a new container save Save one or more images to a tar archive (streamed to STDOUT by default) search Search the Docker Hub for images 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 tag Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE 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 version Show the Docker version information wait Block until one or more containers stop, then print their exit codes
6, Practice
16. Using Docker to install Nginx
# 1. Search image Search suggests you go to the docker hub to search for more details [root@iuwza-an ~/] docker search nginx NAME DESCRIPTION STARS OFFICIAL AUTOMATED nginx Official build of Nginx. 16858 [OK] linuxserver/nginx An Nginx container, brought to you by LinuxS... 168 bitnami/nginx Bitnami nginx Docker Image 131 [OK] ..... # 2. Download Image pull [root@iuwza-an ~/] docker pull nginx Using default tag: latest latest: Pulling from library/nginx 214ca5fb9032: Pull complete 66eec13bb714: Pull complete 17cb812420e3: Pull complete 56fbf79cae7a: Pull complete c4547ad15a20: Pull complete d31373136b98: Pull complete Digest: sha256:2d17cc4981bf1e22a87ef3b3dd20fbb72c3868738e3f307662eb40e2630d4320 Status: Downloaded newer image for nginx:latest docker.io/library/nginx:latest # 3. Run test [root@iuwza-an ~/] docker images REPOSITORY TAG IMAGE ID CREATED SIZE nginx latest de2543b9436b 9 days ago 142MB centos latest 5d0da3dc9764 8 months ago 231MB # -d Background operation # --Name name the container # -p Host port: container port [root@iuwza-an ~/] docker run -d --name nginx01 -p 4455:80 nginx f9ca7d79d21d975fec22d57090e0e572f5aeafbc2c3f72172b8c88a6d102634d [root@iuwza-an ~/] docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES f9ca7d79d21d nginx "/docker-entrypoint...." 7 seconds ago Up 6 seconds 0.0.0.0:4455->80/tcp, :::4455->80/tcp nginx01 #test [root@iuwza-an ~/] curl localhost:4455 <!DOCTYPE html> <html> <head> <title>Welcome to nginx!</title> <style> html { color-scheme: light dark; } body { width: 35em; margin: 0 auto; font-family: Tahoma, Verdana, Arial, sans-serif; } </style> </head> <body> <h1>Welcome to nginx!</h1> <p>If you see this page, the nginx web server is successfully installed and working. Further configuration is required.</p> #Enter container [root@iuwza-an ~/] docker exec -it nginx01 /bin/bash root@f9ca7d79d21d:/# root@f9ca7d79d21d:/ whereis nginx nginx: /usr/sbin/nginx /usr/lib/nginx /etc/nginx /usr/share/nginx root@f9ca7d79d21d:/ cd /etc/nginx/conf.d/ root@f9ca7d79d21d:/etc/nginx/conf.d ls default.conf
Conceptual diagram of port exposure (mapping)
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-Xx8dxV7g-1657791393467)(E:\Typora image save location \59.jpg)]
Thinking: every time we change the nginx configuration file, we need to enter the container? It's very troublesome. If I can provide a mapping path outside the container to modify the file name outside the container, it can be automatically modified inside the container- v data volume technology!
17. Installing Tomcat with Docker
# Download tomcat9.0 # The previous startup is in the background. If the container is stopped, the container can still be found. docker run -it --rm image name is generally used for testing, and it is deleted after use [root@iuwza-an ~/] docker run -it --rm tomcat:9.0 Unable to find image 'tomcat:9.0' locally 9.0: Pulling from library/tomcat 67e8aa6c8bbc: Pull complete #Download the latest version [root@iuwza-an ~/] docker pull tomcat #View downloaded images [root@iuwza-an ~/] docker images REPOSITORY TAG IMAGE ID CREATED SIZE tomcat 9.0 a32ad1e7bf43 9 days ago 685MB tomcat latest 5eb506608219 9 days ago 685MB nginx latest de2543b9436b 9 days ago 142MB #Background mode, exposed port mode, start operation [root@iuwza-an ~/] docker run -d -p 3355:8080 --name tomcat01 tomcat 23f17965140e9618b06e489eae901839642164648a308bf50399875128a1ef0d #No problem with the test curl localhost:3355 #Enter the tomcat container according to the container id [root@iuwza-an ~/] docker exec -it tomcat01 /bin/bash root@23f17965140e:/usr/local/tomcat# #To view the contents of the tomcat container: root@23f17965140e:/usr/local/tomcat ls BUILDING.txt CONTRIBUTING.md LICENSE NOTICE README.md RELEASE-NOTES RUNNING.txt bin conf lib logs native-jni-lib temp webapps webapps.dist work root@23f17965140e:/usr/local/tomcat ll bash: ll: command not found root@23f17965140e:/usr/local/tomcat ls -al total 176 drwxr-xr-x 1 root root 4096 May 18 03:04 . drwxr-xr-x 1 root root 4096 May 11 23:49 .. -rw-r--r-- 1 root root 19010 May 10 21:53 BUILDING.txt -rw-r--r-- 1 root root 6210 May 10 21:53 CONTRIBUTING.md -rw-r--r-- 1 root root 60269 May 10 21:53 LICENSE -rw-r--r-- 1 root root 2333 May 10 21:53 NOTICE -rw-r--r-- 1 root root 3398 May 10 21:53 README.md -rw-r--r-- 1 root root 6908 May 10 21:53 RELEASE-NOTES -rw-r--r-- 1 root root 16515 May 10 21:53 RUNNING.txt drwxr-xr-x 2 root root 4096 May 18 03:04 bin drwxr-xr-x 1 root root 4096 May 27 20:35 conf drwxr-xr-x 2 root root 4096 May 18 03:04 lib drwxrwxrwx 1 root root 4096 May 27 20:35 logs drwxr-xr-x 2 root root 4096 May 18 03:04 native-jni-lib drwxrwxrwx 2 root root 4096 May 18 03:04 temp drwxr-xr-x 2 root root 4096 May 18 03:04 webapps drwxr-xr-x 7 root root 4096 May 10 21:53 webapps.dist drwxrwxrwx 2 root root 4096 May 10 21:53 work #Enter webapps directory root@23f17965140e:/usr/local/tomcat cd webapps root@23f17965140e:/usr/local/tomcat/webapps# ls # Problems found: 1. There are few linux commands. 2.webapps directory is empty # Reason: Alibaba cloud image is the smallest image by default, so unnecessary ones are eliminated # Ensure a minimum operational environment! # Solution: # Put webapps All files under dist can be copied to webapps root@23f17965140e:/usr/local/tomcat cp webapps.dist/* webapps -r #Copy webapps Dist content to webapps root@23f17965140e:/usr/local/tomcat cd webapps root@23f17965140e:/usr/local/tomcat/webapps ls #You can see the copied files ROOT docs examples host-manager manager
Test web page access
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-zDHeh6Bj-1657791393467)(E:\Typora image save location \60.jpg)]
Thinking: we will deploy the project in the future. Is it very troublesome to enter the container every time? If we can provide a mapping path outside the container, such as webapps, and we place items outside, we will automatically synchronize the inside!
18. Deploy es and kibana with Docker
# es exposed many ports! # es consumes a lot of memory # es data generally needs to be placed in the security directory! mount # --net somenetwork ? network configuration # Start elasticsearch docker run -d --name elasticsearch -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:7.6.2 # Test whether es starts successfully [root@iuwza-an ~/]# curl localhost:9200 { "name" : "f51faaa162c4", "cluster_name" : "docker-cluster", "cluster_uuid" : "bsHL_79nTC64thzXE3yJYw", "version" : { "number" : "7.6.2", "build_flavor" : "default", "build_type" : "docker", "build_hash" : "ef48eb35cf30adf4db14086e8aabd07ef6fb113f", "build_date" : "2020-03-26T06:34:37.794943Z", "build_snapshot" : false, "lucene_version" : "8.4.0", "minimum_wire_compatibility_version" : "6.8.0", "minimum_index_compatibility_version" : "6.0.0-beta1" }, "tagline" : "You Know, for Search" } #Check the memory usage of docker container [root@iuwza-an ~/] docker stats CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS f51faaa162c4 elasticsearch 0.00% 1.236GiB / 3.858GiB 32.03% 1.18kB / 942B 8.19kB / 696kB 44 # You can see that the memory consumption is very large. If the machine is 12, it is estimated that it is stuck #If the test is successful, turn off elasticSearch to prevent memory consumption [root@iuwza-an ~/] docker stop f51faaa162c4 f51faaa162c4 #Next, modify the memory limit and the configuration file - e environment configuration modification [root@iuwza-an ~/] docker run -d --name elasticsearch -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" -e ES_JAVA_OPTS="-Xms64m -Xmx512" elasticsearch:7.6.2 docker: Error response from daemon: Conflict. The container name "/elasticsearch" is already in use by container "f51faaa162c46578a128a92d9ec9eb3d04e7a8c32d206311b4bd1c059c59d536". You have to remove (or rename) that container to be able to reuse that name. See 'docker run --help'. #An error is reported here. The container name already exists. Try another test [root@iuwza-an ~/] docker run -d --name elasticsearch02 -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" -e ES_JAVA_OPTS="-Xms64m -Xmx512" elasticsearch:7.6.2 3fc7d64ddddca6b005cfb28b5de0f5c876ecb2adc776be87b2b2f870c8c2c96c [root@iuwza-an ~/] docker stats CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS f51faaa162c4 elasticsearch 0.00% 345.9MiB / 3.858GiB 5.03% 0B / 0B 8.19kB / 696kB 44 [root@iuwza-an ~/]# curl localhost:9200 { "name" : "a4a64dac24b9", "cluster_name" : "docker-cluster", "cluster_uuid" : "uMr0YmQpQ8y-7MUXmELRgw", "version" : { "number" : "7.6.2", "build_flavor" : "default", "build_type" : "docker", "build_hash" : "ef48eb35cf30adf4db14086e8aabd07ef6fb113f", "build_date" : "2020-03-26T06:34:37.794943Z", "build_snapshot" : false, "lucene_version" : "8.4.0", "minimum_wire_compatibility_version" : "6.8.0", "minimum_index_compatibility_version" : "6.0.0-beta1" }, "tagline" : "You Know, for Search" }
**Thinking question: * * use kibana to connect es (elasticSearch)? Think about how the network can connect?
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-P9oxwW7Y-1657791393467)(E:\Typora image save location \61.jpg)]
7, Visualization
19. Portal visual panel installation
- Portal (use this first)
docker run -d -p 8080:9000 \ --restart=always -v /var/run/docker.sock:/var/run/docker.sock --privileged=true portainer/portainer 12
- Rancher(CI/CD reuse)
What is a portal?
Docker graphical interface management tool! Provide a background panel for us to operate.
#Install first docker run -d -p 8089:9000 \ --restart=always -v /var/run/docker.sock:/var/run/docker.sock --privileged=true portainer/portainer [root@iuwza-an ~/] docker run -d -p 8080:9000 \ > --restart=always -v /var/run/docker.sock:/var/run/docker.sock --privileged=true portainer/portainer Unable to find image 'portainer/portainer:latest' locally latest: Pulling from portainer/portainer 772227786281: Pull complete 96fd13befc87: Pull complete 8b2d9b141e4d: Pull complete Digest: sha256:25415d1143949e5dc0b03585365dc8bbe84f443ef116dc27719dc69f23ead35e Status: Downloaded newer image for portain er/portainer:latest 6d400ef1e336eeca03d3022718d6f8ad35513e9f7627d5e039c9bdf2a731f317
Test access: http://IP:8089
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG ygrncjfc-1657791393468) (e:\typora image save location \62.jpg)]
Choose local here
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-0qvFQk9x-1657791393468)(E:\Typora image save location \63.jpg)]
Panel after entering
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-lT7HoeNs-1657791393468)(E:\Typora image save location \64.jpg)]
8, Docker image explanation
20. Federated file system of image principle
What is mirroring
Image is a lightweight and executable independent software assurance, which is used to package the software running environment and the software developed based on the running environment. It contains all the content required to run a software, including code, runtime library, environment variables and configuration files.
All applications can run directly by directly packaging the docker image!
How to get an image
Download from remote warehouse
Others copy it to you
Make an image DockerFile by yourself
Docker image loading principle
UnionFs (Federated file system)
UnionFs(Federated file system): Union File system( UnionFs)It is a layered, lightweight and high-performance file system. It supports the superposition of file system modifications as a submission, and can mount different directories to the same virtual file system at the same time( unite several directories into a single virtual filesystem). Union File system is Docker The basis of mirroring. Images can be inherited through hierarchy. Based on the basic image (without parent image), various specific application images can be made Features: multiple file systems are loaded at the same time, but from the outside, only one file system can be seen. Joint loading will superimpose all levels of file systems, so that the final file system will contain all the underlying files and directories.
Docker image loading principle
docker The image of is actually composed of a layer by layer file system UnionFS. boots(boot file system)Mainly includes bootloader and Kernel, bootloader Mainly guide plus kernel, Linux It will be added at the beginning of startup bootfs File system, in Docker The bottom layer of the image is boots. This layer is similar to our typical Linux/Unix The system is the same, including boot Loader and kernel. When boot After loading, the whole kernel is in memory, and the right to use the memory has been bootfs Transfer to the kernel, and the system will be uninstalled at this time bootfs. rootfs(root file system),stay bootfs above. It contains the typical Linux In the system/dev,/proc,/bin,/etc And other standard directories and documents. rootfs Various operating system distributions, such as Ubuntu, Centos wait.
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-DZ0I2sml-1657791393468)(E:\Typora image save location \65.jpg)]
Usually, the CentOS we install into the virtual machine are several G, why is Docker only 200M?
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-oPDG4HH5-1657791393469)(E:\Typora image save location \66.jpg)]
For a compact OS,rootfs can be very small, and it only needs to include the most basic commands, tools and libraries. Because the underlying layer directly uses the Host's kernel, it only needs to provide rootfs itself. It can be seen that for different Linux distributions, boots are basically the same, and rootfs will be different, so different distributions can share bootfs
The virtual machine is at the minute level, and the container is at the second level!
Hierarchical understanding
We can download an image. Pay attention to the log output of the download. We can see that it is downloading layer by layer
[root@iuwza-an ~/] docker pull redis Using default tag: latest latest: Pulling from library/redis 42c077c10790: Pull complete a300d83d65f9: Pull complete ebdc3afaab5c: Pull complete 31eec7f8651c: Pull complete 9c6a6b89d274: Pull complete 5c8099a4b45c: Pull complete Digest: sha256:1b90dbfe6943c72a7469c134cad3f02eb810f016049a0e19ad78be07040cdb0c Status: Downloaded newer image for redis:latest docker.io/library/redis:latest
Thinking: why should Docker image adopt this hierarchical structure?
The greatest 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 the disk, and only one base image needs to be loaded into the memory, so that all containers can be served, and each layer of the image can be shared.
To view the image hierarchy, you can use the docker image inspect command
[root@iuwza-an ~/] docker image inspect redis:latest [ { "Id": "sha256:53aa81e8adfa939348cd4c846c0ab682b16dc7641714e36bfc57b764f0b947dc", "RepoTags": [ "redis:latest" ], "RepoDigests": [ "redis@sha256:1b90dbfe6943c72a7469c134cad3f02eb810f016049a0e19ad78be07040cdb0c" ], "Parent": "", "Comment": "", "Created": "2022-05-28T10:25:14.900999165Z", "Container": "ea3a9d3caa966b959624cc8ed63e606e32c9b5073de63c1f9f75199030bf518e", "ContainerConfig": { "Hostname": "ea3a9d3caa96", "Domainname": "", "User": "", "AttachStdin": false, "AttachStdout": false, "AttachStderr": false, "ExposedPorts": { "6379/tcp": {} }, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "GOSU_VERSION=1.14", "REDIS_VERSION=7.0.0", "REDIS_DOWNLOAD_URL=http://download.redis.io/releases/redis-7.0.0.tar.gz", "REDIS_DOWNLOAD_SHA=284d8bd1fd85d6a55a05ee4e7c31c31977ad56cbf344ed83790beeb148baa720" ], "Cmd": [ "/bin/sh", "-c", "#(nop) ", "CMD [\"redis-server\"]" ], "Image": "sha256:b058976054e413f88813d52032ca7eb5b84ef92bba5b6b8736ef4907dec4c833", "Volumes": { "/data": {} }, "WorkingDir": "/data", "Entrypoint": [ "docker-entrypoint.sh" ], "OnBuild": null, "Labels": {} }, "DockerVersion": "20.10.12", "Author": "", "Config": { "Hostname": "", "Domainname": "", "User": "", "AttachStdin": false, "AttachStdout": false, "AttachStderr": false, "ExposedPorts": { "6379/tcp": {} }, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "GOSU_VERSION=1.14", "REDIS_VERSION=7.0.0", "REDIS_DOWNLOAD_URL=http://download.redis.io/releases/redis-7.0.0.tar.gz", "REDIS_DOWNLOAD_SHA=284d8bd1fd85d6a55a05ee4e7c31c31977ad56cbf344ed83790beeb148baa720" ], "Cmd": [ "redis-server" ], "Image": "sha256:b058976054e413f88813d52032ca7eb5b84ef92bba5b6b8736ef4907dec4c833", "Volumes": { "/data": {} }, "WorkingDir": "/data", "Entrypoint": [ "docker-entrypoint.sh" ], "OnBuild": null, "Labels": null }, "Architecture": "amd64", "Os": "linux", "Size": 116786752, "VirtualSize": 116786752, "GraphDriver": { "Data": { "LowerDir": "/var/lib/docker/overlay2/b06a54049cf72a03327fb8f260b33848083acf154a0d5c8b897fc8c6a6da71fb/diff:/var/lib/docker/overlay2/a4b9ccba67fccb1e3cb55cca48b39999334b405e81c1295d1b9b6d4fcb88509f/diff:/var/lib/docker/overlay2/50ec4f9a10f6a32f4532efd9a02ee5dcb97e9d04b8a668c12b0b781160c76609/diff:/var/lib/docker/overlay2/b9b692df2a99752bcd34146441aa3b15f7008368b4210eec589deb8cfceae862/diff:/var/lib/docker/overlay2/22b0145f46976f3861d7d0b479a41be0c714618734b3475b59e4bfdbb348d8b1/diff", "MergedDir": "/var/lib/docker/overlay2/07717dc5ba0efc5233d1f8b93447783a6bdaff0fe14e6e14ed59415f413859fd/merged", "UpperDir": "/var/lib/docker/overlay2/07717dc5ba0efc5233d1f8b93447783a6bdaff0fe14e6e14ed59415f413859fd/diff", "WorkDir": "/var/lib/docker/overlay2/07717dc5ba0efc5233d1f8b93447783a6bdaff0fe14e6e14ed59415f413859fd/work" }, "Name": "overlay2" }, "RootFS": { "Type": "layers", "Layers": [ "sha256:ad6562704f3759fb50f0d3de5f80a38f65a85e709b77fd24491253990f30b6be", "sha256:49cba0f0997b2bb3a24bcfe71c7cbd6e9f6968ef7934e3ad56b0f1f9361b6b91", "sha256:309498e524b3e2da1f036d00cd5155e0b74cf9e1d964a3636c8ed63ca4a00d43", "sha256:f7c9b429437f7ada2d3d455ac4ea90ff38e0cb7ef2551b08d152264b74116309", "sha256:4dabdd56bbf16307e2328cb6ed1d42b0bb9b8f40551421271c0b38dc9a685dcc", "sha256:ea450ad6ef893e998f88a35dc9cc22f952c62b88d58f948344cf4eda1a6264fc" ] }, "Metadata": { "LastTagTime": "0001-01-01T00:00:00Z" } } ]
understand
All Docker images start from a basic image layer. When modifying or adding new content, a new image layer will be created on top of the current image layer.
For a simple example, if you create a new image based on Ubuntu Linux16.04, this is the first layer of the new image; If you add Python packages to this image,
A second mirror layer will be created above the basic mirror layer; If you continue to add a security patch, you will create a third image layer, which currently includes three image layers, as shown in the following figure (this is just a simple example for demonstration).
While adding an additional mirror layer, the mirror always remains the combination of all current mirrors. Understand this.
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-w6tPTk7e-1657791393469)(E:\Typora image save location \68.jpg)]
It is very important to understand that while adding an additional mirror layer, the mirror always remains the combination of all current mirrors. A simple example is given in the figure below. Each image layer contains three files, while the image contains six files from two image layers.
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG xsopgjyu-1657791393469) (e:\typora image save location \69.jpg)]
The image layer in the above figure is slightly different from that in the previous figure. The main purpose is to facilitate the display of files
The following figure shows a slightly complex three-level image. Externally, there are only six files in the entire image, because file 7 in the top layer is a newer version of file 5.
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-y1toK23t-1657791393470)(E:\Typora image save location \70.jpg)]
In this case, the files in the upper image layer overwrite the files in the lower image layer. In this way, the updated version of the file is added to the image as a new image layer
Docker implements the image layer stack through the storage engine (the new version adopts the snapshot mechanism), and ensures that multiple image layers are displayed as a unified file system
AUFS, Overlay2, Device Mapper, Btrfs, and ZFS are available storage sources on Linux. As the name suggests, each storage engine is based on the corresponding file system or block device technology in Linux, and each storage engine has its unique performance characteristics.
Docker only supports windowsfilter as a storage engine on Windows, which implements layering and CoW based on NTFS file system.
The following figure shows the same three-layer image as the system display. All mirror layers are stacked and combined to provide a unified view.
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-dsi9jjvW-1657791393470)(E:\Typora image save location \71.jpg)]
characteristic
Docker images are read-only. When the container starts, a new writable layer is loaded on top of the image!
This layer is what we usually call the container layer. What is under the container is called the image layer!
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-qSgJSJ7o-1657791393470)(E:\Typora image save location \72.jpg)]
Commit image
docker commit Submit the container as a new copy # The principle of command is similar to that of git docker commit -m="Descriptive information" -a="author" container id Target image name:[edition TAG]
Field test
# 1. Start a default tomcat [root@iuwza-an ~/] docker run -d -p 8080:8080 tomcat e523eee7589133d05ca98f769751cf796dd0aa88b2c0a06f984bc888f9052088 [root@iuwza-an ~/] docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES e523eee75891 tomcat "catalina.sh run" 36 seconds ago Up 35 seconds 0.0.0.0:8080->8080/tcp, :::8080->8080/tcp charming_mahavira # 2. It is found that there is no webapps application for this default tomcat, and there is no file under the official image default webapps! #docker exec -it container id /bin/bash [root@iuwza-an ~/] docker exec -it e523eee75891 /bin/bash root@e523eee75891:/usr/local/tomcat# # 3. From webapps Dist copy files into webapp root@e523eee75891:/usr/local/tomcat# cp -r webapps.dist/* webapps root@e523eee75891:/usr/local/tomcat# cd webapps root@e523eee75891:/usr/local/tomcat/webapps# ls ROOT docs examples host-manager manager # 4. Adjust the operated container to an image through commit! We can use our modified image in the future without copying webapps every time The file under dist is in webapps. This is a modified image of ourselves. docker commit -m="Descriptive information" -a="author" container id Target image name:[TAG] docker commit -a="lijunan" -m="add webapps app" container id tomcat02:1.0
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-RTHH4uY1-1657791393470)(E:\Typora image save location \73.jpg)]
**Learning method: * * understand the concept, but be sure to practice it. Finally, combine theory with practice to get this knowledge
If you want to save the state of the current container, you can commit it and get an image, just like we use the snapshot of virtual machine.
Here is the entry Docker!
9, Docker container data volume
What is a container data volume?
Review of Dcoker's concept:
Package the application into an image
If all the data is in the container, we will lose the data if we delete the container! > Requirements: data can be persistent
Mysql, container deletion = delete database and run! > Requirement: MySQL data can be stored locally!
There can be a data sharing technology between containers! The data generated in the Docker container is synchronized locally
This is volume technology! Mount the directory, mount the directory in our container to Linux!
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-Nyftd6wa-1657791393471)(E:\Typora image save location \74.jpg)]
**To sum up: * * container persistence and synchronization operations! Data can also be shared between containers!
21. Using data volumes
Mode 1:Mount directly with commands -V docker run -it -V Host Directory:Contents in container #test [root@iuwza-an ~/]# docker run -it -v/home/ceishi:/home centos /bin/bash [root@83182883fa4b /]# [root@iuwza-an /home/]# ls ceishi [root@iuwza-an /home/]# cd ceishi/ [root@iuwza-an /home/ceishi/]# ls [root@iuwza-an /home/ceishi/]# #When starting up, we can inspect the container id through docker "Mounts": [ { "Type": "bind", "Source": "/home/ceishi", "Destination": "/home", "Mode": "", "RW": true, "Propagation": "rprivate" } ],
Synchronization of test files
# Create a test file in the container to see if it can be synchronized [root@83182883fa4b home] touch test.go [root@83182883fa4b home] ls test.go # Then check whether /home/ceishi is synchronized outside the container [root@iuwza-an ~/] ls /home/ceishi/ test.go
Test 2: stop the container, modify the directory test file outside the container, and then start the container to see whether the file content is synchronized and consistent
# 1. Stop the container first [root@iuwza-an ~/] docker stop 83182883fa4b 83182883fa4b # 2. Modify the content of the test file vim /home/ceishi/test.go hello i love you # 3. Restart the container to check whether the contents of the test file are consistent [root@iuwza-an ~/] docker start 83182883fa4b 83182883fa4b [root@iuwza-an ~/] docker attach 83182883fa4b [root@83182883fa4b /]# [root@83182883fa4b /] cat home/test.go hello i love you
Benefits: we only need to modify locally in the future, and the container will be automatically synchronized
Actual combat: install MySQL
**Thinking questions: **MySQL data persistence!
#Get image [root@iuwza-an ~/] docker pull mysql:5.7 #To run the container, you need to mount the data! #To install and start mysq1, you need to configure the password, which should be paid attention to! #Official test: docker run --name some -mysq1 -e MYSQL_ ROOT_ PASSWORD=my-secret-pw -d mysq1:tag #Start our -d Background operation -p Port mapping -v Volume mount -e Environment configuration --name Container name [root@iuwza-an ~/] docker run -d -p 3308:3306 -v /home/mysql/conf:/etc/mysql/conf.d -v /home/mysql/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=123456 --name=mysql01 mysql:5.7 0445a9f2093e03c3a26c55a9691df4f3af8aae360025f8c8e33167af69f4c738 # After successful startup, let's use Navicat locally to connect and test # Navicat connects to the 3308 - 3308 of the server and the 3306 mapping in the container. At this time, we can connect! #Create a database in the local test and check whether the mapped path is ok!
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-N5ufYoE5-1657791393471)(E:\Typora image save location \75.jpg)]
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-RbMcFU6W-1657791393471)(E:\Typora image save location \76.jpg)]
Suppose we delete the container and try it!
[root@iuwza-an /home/mysql/data/]# docker rm -f mysql01 mysql01 [root@iuwza-an /home/mysql/data/]# docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 83182883fa4b centos "/bin/bash" About an hour ago Up 58 minutes compassionate_ishizaka e523eee75891 tomcat "catalina.sh run" 2 hours ago Up 2 hours 0.0.0.0:8080->8080/tcp, :::8080->8080/tcp charming_mahavira a94e1bf71fe5 portainer/portainer "/portainer" 4 hours ago Up 4 hours 0.0.0.0:8089->9000/tcp, :::8089->9000/tcp blissful_fermi # You can see that the container has been deleted #Then check the files in the data directory [root@iuwza-an /home/mysql/data/]# ls auto.cnf ca.pem client-key.pem ibdata1 ib_logfile1 mysql private_key.pem server-cert.pem sys ca-key.pem client-cert.pem ib_buffer_pool ib_logfile0 ibtmp1 performance_schema public_key.pem server-key.pem test
It can be found that the data volume we mounted locally is still not lost, which realizes the function of container data persistence!
22. Named and anonymous mount
#Anonymous mount -v Path in container! docker run -d -P --name nginx01 -v /ect/nginx nginx #View all volume s [root@iuwza-an ~/] docker volume ls DRIVER VOLUME NAME local 6f8ffd53c5d3564db129139c10f23e6473bf52ca2f4614c447c1b2147d35bf5f #It is found here that this is anonymous mount. We only write the path inside the container in -V, not the path outside the container! #Named mount [root@iuwza-an ~/] docker run -d -P --name nginx01 -v test:/etc/nginx nginx 345908c2f4f179659199830d4e3cf10b9aba275a6ff40fe7085fbb7901fac69d [root@iuwza-an ~/] docker volume ls DRIVER VOLUME NAME local 6f8ffd53c5d3564db129139c10f23e6473bf52ca2f4614c447c1b2147d35bf5f local 5602566d69740620634635e00572cc892c31c23ed8ad003207880de7c04ba3d6 local a60663a09e9b655b15d970db439bb6a46acd5ffe079cd97b72872f4aab83a1a9 local b60e90fa1134b2c4f15ac6b766f7d4404ee2ba7ad1eeb517c58c5c5b4e74ff61 local b206882b0a2f27d6880c2caec59e5bd582d8a2badb69d70143c09e28624cac23 local test # Pass -v volume name: path in container # Check this volume [root@iuwza-an ~/] docker volume inspect test [ { "CreatedAt": "2022-05-29T22:30:00+08:00", "Driver": "local", "Labels": null, "Mountpoint": "/var/lib/docker/volumes/test/_data", "Name": "test", "Options": null, "Scope": "local" } ]
All the volumes in the docker container are in /var/lib/docker/volumes/ volume name if no directory is specified/_ data
We can easily find one of our volumes through named mount, which is used in most cases
#How to determine whether it is a named mount, an anonymous mount, or a specified path mount! -v Path in container #Anonymous mount -v Volume name:Path in container #Named mount -v /Host path::Path in container #Specify the path to mount!
expand
#Change the read and write permissions through -V path in the container: ro rw ro #read-only rw #Readable and writable #Once the container permission is set, the container will limit the content we mount! docker run -d -P --name nginx02 -v test:/etc/nginx:ro nginx docker run -d -P --name nginx02 -v test:/etc/nginx:rw nginx # As long as ro sees ro, it means that this path can only be operated through the host machine, and it cannot be operated inside the container!
23. Get to know Dockerfile for the first time
Dockerfile is the build file used to build the docker image! Command script! Experience it first!
Through this script, you can generate an image. The image is layer by layer. The script commands one by one, and each command is a layer!
# Create a dockerfile whose name can be randomly suggested [root@iuwza-an /home/]# mkdir -p docker-test-volume vim dockerfile1 # Content directive (upper case) parameters in the file [root@iuwza-an /home/docker-test-volume/]# cat dockerfile1 FROM centos VOLUME ["volume01","volume02"] CMD echo "-----END-----" CMD /bin/bash # Every command here is a layer of image >> Explanation: -f #File path -t #describe [root@iuwza-an /home/docker-test-volume/] docker build -f /home/docker-test-volume/dockerfile1 -t lijunan/centos:1.0 . Sending build context to Docker daemon 2.048kB Step 1/4 : FROM centos ---> 5d0da3dc9764 Step 2/4 : VOLUME ["volume01","volume02"] ---> Running in 6f14a932895e Removing intermediate container 6f14a932895e ---> af858afee400 Step 3/4 : CMD echo "-----END-----" ---> Running in de6d5f6ad52e Removing intermediate container de6d5f6ad52e ---> 9257c9ad21a7 Step 4/4 : CMD /bin/bash ---> Running in 233afd1b216c Removing intermediate container 233afd1b216c ---> 37a758c6b5ff Successfully built 37a758c6b5ff Successfully tagged lijunan/centos:1.0 # Start your own container
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-auwM4kWa-1657791393472)(C:\Users\ Li Junan \AppData\Roaming\Typora\typora-user-images\image-20220529233437748.png)]
There must be a synchronized directory between this volume and the outside!
When we first operated, we didn't write anything, only the directory inside the container, so it was just an anonymous mount!
Check the path where the volume is mounted:
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-HWhUM7Rf-1657791393472)(E:\Typora image save location \78.jpg)]
Test whether the created files are synchronized
# First create the test file in the volume01 directory in the container [root@49212b241204 /]# cd volume01/ [root@49212b241204 volume01]# ls [root@49212b241204 volume01]# touch container.txt [root@49212b241204 volume01]# ls container.txt # Then enter the path of volume01 to check that it has been synchronized cd /var/lib/docker/volumes/105dd901552ad35dbe1277f70ebed612acefad85c11efafed4e8ac121fdd2a3 ls container.txt
We will use this method a lot in the future, because we usually build our own image!
Assuming that there is no mounted volume when building the image, you need to manually mount the image -v volume name: path in the container!
24. Data volume container
Multiple MySQL synchronization data!
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG nvzpxlca-1657791393472) (e:\typora image save location \79.jpg)]
Start the three containers through the image we just wrote
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-B7A4l4rZ-1657791393473)(E:\Typora image storage location \80.jpg)]
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-u9bmdhfe-1657791393473)(E:\Typora image save location \81.jpg)]
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-DvW4XVqc-1657791393473)(E:\Typora image save location \82.jpg)]
Test: delete docker01 and check whether docker02 and docker03 can still access this file
It can still be accessed after the test
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-5jkwi1mH-1657791393474)(E:\Typora image storage location \84)]
Data sharing with multiple MySQL
[root@iuwza-an ~/] docker run -d -p 3308:3306 -v /etc/mysql/conf.d -v /var/lib/mysql -e MYSQL_ROOT_PASSWORD=123456 --name mysql01 mysql:5.7 [root@iuwza-an ~/] docker run -d -p 3309:3306 -e MYSQL_ROOT_PASSWORD=123456 --name mysql02 --volumes-from mysql01 mysql:5.7 mysql:5.7 # You can see that both databases are running [root@iuwza-an ~/] docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 8a0859ae3c25 mysql:5.7 "docker-entrypoint.s..." 6 seconds ago Up 5 seconds 33060/tcp, 0.0.0.0:3309->3306/tcp, :::3309->3306/tcp mysql02 c56c8bfd7d3d mysql:5.7 "docker-entrypoint.s..." About a minute ago Up About a minute 33060/tcp, 0.0.0.0:3308->3306/tcp, :::3308->3306/tcp mysql01 # Next, we create a test database in 01 to see if 02 is synchronized # 1. Enter mysql01 database first #Review command: docker exec -it container name [root@iuwza-an ~/] docker exec -it mysql01 /bin/bash root@c56c8bfd7d3d:/# root@c56c8bfd7d3d:/# root@c56c8bfd7d3d:/# root@c56c8bfd7d3d:/# ls bin boot dev docker-entrypoint-initdb.d entrypoint.sh etc home lib lib64 media mnt opt proc root run sbin srv sys tmp usr var root@c56c8bfd7d3d:/# cd /var/lib/mysql root@c56c8bfd7d3d:/var/lib/mysql# ls auto.cnf ca.pem client-key.pem ib_logfile0 ibdata1 mysql private_key.pem server-cert.pem sys ca-key.pem client-cert.pem ib_buffer_pool ib_logfile1 ibtmp1 performance_schema public_key.pem server-key.pem # Create a test test01 root@c56c8bfd7d3d:/var/lib/mysql# touch test01 root@c56c8bfd7d3d:/var/lib/mysql# ls auto.cnf ca.pem client-key.pem ib_logfile0 ibdata1 mysql private_key.pem server-cert.pem sys ca-key.pem client-cert.pem ib_buffer_pool ib_logfile1 ibtmp1 performance_schema public_key.pem server-key.pem test01 #Enter mysql02 to check whether it is synchronized [root@iuwza-an ~/] docker exec -it mysql02 /bin/bash root@8a0859ae3c25:/# ls bin boot dev docker-entrypoint-initdb.d entrypoint.sh etc home lib lib64 media mnt opt proc root run sbin srv sys tmp usr var root@8a0859ae3c25:/# cd /var/lib/mysql root@8a0859ae3c25:/var/lib/mysql# ls auto.cnf ca.pem client-key.pem ib_logfile0 ibdata1 mysql private_key.pem server-cert.pem sys ca-key.pem client-cert.pem ib_buffer_pool ib_logfile1 ibtmp1 performance_schema public_key.pem server-key.pem test01 #Then you can see that the data synchronization of the two containers can be realized!
Conclusion:
For the transfer of configuration information between containers, the life cycle of data volume containers lasts until there is no container.
But once you persist to the local, the local data will not be deleted at this time!
10, DockerFile
25. DockerFile introduction
dockerfile is the file used to build docker image! Command parameter script!
Construction steps:
1. Write a dockerfile file
2. Build docke build into an image
3. docker run running image
4. docker push release image (DcokerHub, Alibaba cloud image warehouse!)
Check out what the official does?
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG kcanrhvm-1657791393474) (e:\typora image storage location \86.png)]
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-t5h4Fhiw-1657791393474)(E:\Typora image save location \87.png)]
Many official images are basic packages without many functions. We usually build our own images!
Since the official can make images, so can we!
26. DockerFile construction process
Basic knowledge:
1. Each reserved keyword (instruction) must be capitalized
2. The execution process is from top to bottom
3. # indicates notes
4. Each instruction will create and submit a new image layer and submit it!
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-756wU6Sf-1657791393475)(E:\Typora image save location \88.png)]
Dockerfile is development oriented. We need to write a dockerfile file to publish projects and mirror them in the future. This file is very simple!
Docker image has gradually become an enterprise delivery standard, which must be mastered!
Steps: development, deployment, operation and maintenance... Are indispensable!
DockerFile: build the file, define all the steps, and source code
DockerImages: build the generated image through DokcerFile, and finally release and run the product!
Docker container: the container is like an image running to provide services
27. DockerFile instructions
We used to use others. Now after knowing these instructions, we can practice writing a mirror image by ourselves!
FROM # Basic image, everything starts from here MAINTAINER # Who wrote the image, name + email RUN # Commands to run when building an image ADD # Step: tomcat image, this tomcat compressed package, add content WORKER # Mirrored working directory VLOUME # Mounted directory EXPOSE # Exposed port configuration CMD # Specify the command to run when this container starts. Only the last one will take effect and can be replaced ENTRYPOINT # Specify the command to be run when the container is started, and you can append the command ONBUILD # When building an inherited DockerFile, the ONBUILD Instruction > trigger instruction will be run. COPY # Similar to ADD, copy our files to the image ENV # Set environment variables during construction
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG owhhphrd-1657791393475) (e:\typora image save location \89.png)]
Actual test:
99% of the images in Docker Hub are FROM scratch, and then configure the required software and configuration to build!
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-kEZ0hsfs-1657791393475)(E:\Typora image storage location \90.png)]
Create your own CentOS:
# 1. Write DockerFile file [root@iuwza-an /home/dockerfile/] vim mydocker-centos [root@iuwza-an /home/dockerfile/] cat mydocker-centos FROM centos:7 MAINTAINER An<2952001366@qq.com> ENV MYPATH /usr/local WORKDIR /My_WORKDIR RUN yum install vim -y RUN yum install net-tools -y EXPOSE 80 CMD echo $MYPATH CMD echo "-----end-----" CMD /bin/bash # 2. Build an image from this file # Command docker build -f dockerfiile file path -t image name: [tag] docker build -f mydocker-centos -t mycentos:2.0 . # It will be carried out step by step Successfully built 20763092a712 Successfully tagged mycentos:2.0 # 3. Test run docker run -it mycentos:2.0
Test run:
Comparison: Previous native Centos
root@iuwza-an:[2022-06-01 01:47:00]$/root docker run -it 5d0da3dc9764 [root@9108f8b6acb1 /]# [root@9108f8b6acb1 /]# pwd / [root@9108f8b6acb1 /]# vim bash: vim: command not found [root@9108f8b6acb1 /]# ifconfig bash: ifconfig: command not found [root@9108f8b6acb1 /]#
After we add the image
root@iuwza-an:[2022-06-01 01:48:18]$/ docker run -it mycentos:2.0 [root@0f9595100ab3 My_WORKDIR]# ls [root@0f9595100ab3 My_WORKDIR]# pwd /My_WORKDIR [root@0f9595100ab3 My_WORKDIR]# ifconfig eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 172.17.0.5 netmask 255.255.0.0 broadcast 172.17.255.255 ether 02:42:ac:11:00:05 txqueuelen 0 (Ethernet) RX packets 8 bytes 656 (656.0 B) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 0 bytes 0 (0.0 B) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536 inet 127.0.0.1 netmask 255.0.0.0 loop txqueuelen 1000 (Local Loopback) RX packets 0 bytes 0 (0.0 B) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 0 bytes 0 (0.0 B) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 [root@0f9595100ab3 My_WORKDIR]# vim test
We can list the history of changes made locally
root@iuwza-an:[2022-06-01 01:52:59]$/ docker history 20763092a712 IMAGE CREATED CREATED BY SIZE COMMENT 20763092a712 8 hours ago /bin/sh -c #(nop) CMD ["/bin/sh" "-c" "/bin... 0B c223f2778901 8 hours ago /bin/sh -c #(nop) CMD ["/bin/sh" "-c" "echo... 0B 95097e06e4de 8 hours ago /bin/sh -c #(nop) CMD ["/bin/sh" "-c" "echo... 0B 0e4989401e60 8 hours ago /bin/sh -c #(nop) EXPOSE 80 0B 9abd7a3a9cb6 8 hours ago /bin/sh -c yum -y install net-tools 171MB 454300075d97 8 hours ago /bin/sh -c yum -y install vim 226MB 984a810ff5f6 8 hours ago /bin/sh -c #(nop) WORKDIR /My_WORKDIR 0B 7bc039f1bc28 8 hours ago /bin/sh -c #(nop) ENV MYPATH=/usr/local 0B 1855a88accee 8 hours ago /bin/sh -c #(nop) MAINTAINER An<2952001366@... 0B eeb6ee3f44bd 8 months ago /bin/sh -c #(nop) CMD ["/bin/bash"] 0B <missing> 8 months ago /bin/sh -c #(nop) LABEL org.label-schema.sc... 0B <missing> 8 months ago /bin/sh -c #(nop) ADD file:b3ebbe8bd304723d4... 204MB
We usually get a mirror image, so we can study how he did it?
Difference between CMD and ENTRYPOINT
CMD # Specify the command to run when this container starts. Only the last one will take effect and can be replaced ENTRYPOINT # Specify the command to be run when the container is started, and you can append the command
Test CMD
# 1. Write test CMD file root@iuwza-an:[2022-06-01 03:03:00]$/home/dockerfile vim dockerfile-test-cmd FROM centos CMD ["ls","-a"] # 2. Build CMD test image root@iuwza-an:[2022-06-01 03:03:00]$/home/dockerfile docker build -f dockerfile-test-cmd -t test-cmd . ... .... Successfully built 7dfbf1300bcd Successfully tagged test-cmd:latest # 3. Run the test cmd to see the effect root@iuwza-an:[2022-06-01 03:03:32]$/home/dockerfile docker run -it 7dfbf1300bcd . .dockerenv dev home lib64 media opt root sbin sys usr .. bin etc lib lost+found mnt proc run srv tmp var # Want to append a command -l LS -al root@iuwza-an:[2022-06-01 03:04:10]$/home/dockerfile docker run -it 7dfbf1300bcd -l docker: Error response from daemon: failed to create shim: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "-l": executable file not found in $PATH: unknown. ERRO[0000] error waiting for container: context canceled # cmd cleanup -l replaced CMD ["ls","-a"] command, -l is not a command, so an error is reported!
Test ENTRYPOINT
# 1. Write test ENTRYPOINT file root@iuwza-an:[2022-06-01 03:04:32]$/home/dockerfile vim dockerfile-test-entrypoint FROM centos ENTRYPOINT ["ls","-a"] # 2. Build ENTRYPOINT test image root@iuwza-an:[2022-06-01 03:13:19]$/home/dockerfile docker build -f dockerfile-test-entrypoint -t test-entrypoint . .... .... Successfully built 6fe1bfb89305 Successfully tagged test-entrypoint:latest # 3. Run the test ENTRYPOINT and you can see that it is no different from the above CMD effect root@iuwza-an:[2022-06-01 03:13:55]$/home/dockerfile docker run -it 6fe1bfb89305 . .dockerenv dev home lib64 media opt root sbin sys usr .. bin etc lib lost+found mnt proc run srv tmp var # Our additional command is directly spliced after our ENTRYPOINT command root@iuwza-an:[2022-06-01 03:14:15]$/home/dockerfile docker run -it 6fe1bfb89305 -l total 56 drwxr-xr-x 1 root root 4096 May 31 19:14 . drwxr-xr-x 1 root root 4096 May 31 19:14 .. -rwxr-xr-x 1 root root 0 May 31 19:14 .dockerenv lrwxrwxrwx 1 root root 7 Nov 3 2020 bin -> usr/bin drwxr-xr-x 5 root root 360 May 31 19:14 dev drwxr-xr-x 1 root root 4096 May 31 19:14 etc drwxr-xr-x 2 root root 4096 Nov 3 2020 home lrwxrwxrwx 1 root root 7 Nov 3 2020 lib -> usr/lib lrwxrwxrwx 1 root root 9 Nov 3 2020 lib64 -> usr/lib64 drwx------ 2 root root 4096 Sep 15 2021 lost+found drwxr-xr-x 2 root root 4096 Nov 3 2020 media drwxr-xr-x 2 root root 4096 Nov 3 2020 mnt drwxr-xr-x 2 root root 4096 Nov 3 2020 opt dr-xr-xr-x 170 root root 0 May 31 19:14 proc dr-xr-x--- 2 root root 4096 Sep 15 2021 root drwxr-xr-x 11 root root 4096 Sep 15 2021 run lrwxrwxrwx 1 root root 8 Nov 3 2020 sbin -> usr/sbin drwxr-xr-x 2 root root 4096 Nov 3 2020 srv dr-xr-xr-x 13 root root 0 May 29 15:19 sys drwxrwxrwt 7 root root 4096 Sep 15 2021 tmp drwxr-xr-x 12 root root 4096 Sep 15 2021 usr drwxr-xr-x 20 root root 4096 Sep 15 2021 var
Many commands in DockerFile are very similar. We need to understand their differences. Our best learning is to compare them and test the effect!
Actual combat: Tomcat image
1. Prepare the image file, tomcat compressed package and jdk compressed package
2. Write a dockerfile file, officially named dockerfile, and build will automatically find this file, so -f is not required
3. Build image
4. Start the image
5. Access test
6. Release test (because the volume is mounted, we can directly write the project locally and release it!)
# 1. Environmental preparation # root@iuwza-an:[2022-06-01 06:15:06]$/home/tomcat ls apache-tomcat-9.0.22.tar.gz jdk-8u11-linux-x64.tar.gz # 2. Write Dockerfile file root@iuwza-an:[2022-06-01 06:15:28]$/home/tomcat cat Dockerfile FROM centos:7 MAINTAINER An<2952001366@qq.com> COPY readme.txt /usr/local/readme.txt ADD jdk-8u11-linux-x64.tar.gz /usr/local/ ADD apache-tomcat-9.0.22.tar.gz /usr/local/ RUN yum -y install vim ENV MYPATH /usr/local WORKDIR $MYPATH 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-9.0.22 ENV CATALINA_BASH /usr/local/apache-tomcat-9.0.22 ENV PATH $PATH:$JAVA_HOME/bin:$CATALINA_HOME/lib:$CATALINA_HOME/bin EXPOSE 8080 CMD /usr/local/apache-tomcat-9.0.22/bin/startup.sh && tail -F /usr/local/apache-tomcat-9.0.22/bin/logs/catalina.out Note: the path of configuration file and instruction vocabulary must be written carefully! # 3. Build image root@iuwza-an:[2022-06-01 06:01:24]$/home/tomcat docker build -t mytomcat . .... .... .... Successfully built 35b4362a64b2 Successfully tagged mytomcat:latest # You can see that the build is successful # 4. Next, start mirroring root@iuwza-an:[2022-06-01 06:05:16]$/home/tomcat docker run -d -p 9095:8080 --name antomcat -v /home/tomcat/test:/usr/local/apache-tomcat-9.0.22/webapps/test -v /home/tomcat/tomcatlogs:/usr/local/apache-tomcat-9.0.22/logs mytomcat # You can see that the startup is successful root@iuwza-an:[2022-06-01 06:07:57]$/home/tomcat docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES bddb7836a88f mytomcat "/bin/sh -c '/usr/lo..." 5 seconds ago Up 3 seconds 0.0.0.0:9095->8080/tcp, :::9095->8080/tcp antomcat Note: use in the command line first curl localhost:9095 Visit the test and see if there is an error: curl: (56) Recv failure: Connection reset by peer Just check Dockerfile File it
Effect of access test: http://IP:9095
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG uvoylgu-1657791393476) (e:\typora image save location \91.png)]
Create a new web under WEB-INF under the corresponding directory of tomcat XML, index JSP test file
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> </web-app>
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Hello,Welcome to my site</title> </head> <body> Hello World!<br/> <% System.out.println("----my test web logs----"); %> </body> </html>
Effect: the project is published successfully, and the test visit is ok!
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-r7zCURFN-1657791393476)(E:\Typora image save location \92.jpg)]
Our next development steps: we need to master the preparation of Dockerfile! After that, we use the docker image to publish and run!
28. Publish your own image
DockerHub
1. At address https://hub.docker.com/ Register your account! Be sure to log in to this account!
2. Submit your own image on our own server!
docker login --help Usage: docker login [OPTIONS] [SERVER] Log in to a Docker registry. If no server is specified, the default is defined by the daemon. Options: -p, --password string Password --password-stdin Take the password from stdin -u, --username string Username root@iuwza-an:[2022-06-02 21:09:31]$/root docker login -u 21978748 Password: WARNING! Your password will be stored unencrypted in /root/.docker/config.json. Configure a credential helper to remove this warning. See https://docs.docker.com/engine/reference/commandline/login/#credentials-store Login Succeeded #You can see the success
3. After logging in, you can submit the image, which is a one-step docker push
# push to your server! docker push mytomcat Using default tag: latest The push refers to repository [docker.io/library/mytomcat] fa718d90998b: Preparing 0335213fd01b: Preparing f5de58ab048b: Preparing 91cddd72e939: Preparing 174f56854903: Preparing denied: requested access to the resource is denied #access was denied # Is there a problem with push ing images? The push refers to repository [docker.io/an/mytomcat] An image does not exist locally with the tag: an/mytomcat # Solve it. Add a tag or log in again root@iuwza-an:[2022-06-02 21:31:41]$/root/.docker docker tag 6b63c72c73e4 21978748/mytomcat-an:2.0 # Docker can push it up. Try to bring the version number when pushing! docker tag 6b63c72c73e4 21978748/mytomcat-an:2.0 root@iuwza-an:[2022-06-02 21:33:11]$/root/.docker docker push 21978748/mytomcat-an:2.0 The push refers to repository [docker.io/21978748/mytomcat-an] fa718d90998b: Pushed 0335213fd01b: Pushed f5de58ab048b: Pushed 91cddd72e939: Pushed 174f56854903: Pushed 2.0: digest: sha256:25c36aee45a306bbad08eada247da2065ab333ed6088477f0d1e12dc2f9cafbb size: 1373 # You can find that the push up is also pushed according to the level
Alibaba cloud
1. Register an account on Alibaba cloud and log in to Alibaba cloud!
2. Find the container image service and create a namespace!
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-9WxtY196-1657791393476)(E:\Typora image save location \94.png)]
3. Create container image!
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-G1EwHPqV-1657791393477)(E:\Typora image save location \93.jpg)]
4. Browse Alibaba cloud push image document
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-yZ99y3e0-1657791393477)(E:\Typora image save location \95.png)]
For Alibaba cloud container image use, please refer to the official address!
29. Summary
Review what you have learned before and understand the flow chart below
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-c601eIyT-1657791393477)(E:\Typora image save location \96.png)]
11, Docker network
30. Understand docker0
Test (empty all images and containers to facilitate learning the network!)
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-nh4zcyQT-1657791393477)(E:\Typora image save location \97.jpg)]
Three networks
Thinking question: how does docker handle container network access?
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-z6SnMVzW-1657791393478)(E:\Typora image save location \98.jpg)]
# Start a tomcat container test [root@iuwza-an ~] docker run -d -P --name tomcat01 tomcat # View container internal address ip addr will get a eth0@if9 ip address, assigned by docker! [root@iuwza-an ~] docker exec -it tomcat01 ip addr # Note: if the following error is reported in this command, it is because tomcat is too compact and there is no ip addr command in it OCI runtime exec failed: exec failed: unable to start container process: exec: "ip": executable file not found in $PATH: unknown # Solve problem 1: # Enter tomcat01 container [root@iuwza-an ~] docker exec -it tomcat01 /bin/bash # It's true that no! root@c0ac350e24fd:/usr/local/tomcat# yum install -y iproute2 bash: yum: command not found # I first used yum. I thought Yum was not available, so I had to apt! root@c0ac350e24fd:/usr/local/tomcat# yum install -y iproute2 bash: yum: command not found # As a result, apt reported an error, which was caused by the fact that the image of the package management tool apt was foreign and the download speed was too slow root@c0ac350e24fd:/usr/local/tomcat# apt install -y iproute2 Reading package lists... Done Building dependency tree... Done Reading state information... Done E: Unable to locate package iproute2 # Solve problem 2: # Enter the configuration file in the container cd /etc/apt # View directory information ls cat sources.list # backups cat sources.list.backup cp sources.list ./sources.list.backup cd ../ # Replace sources by overwriting + appending List file echo 'deb https://mirrors.aliyun.com/debian bullseye main'>sources.list echo 'deb https://mirrors.aliyun.com/debian-security bullseye-security main'>>sources.list echo 'deb https://mirrors.aliyun.com/debian bullseye-updates main'>>sources.list # Execute the following update command: apt-get update -y # Execute the download iproute2 command: apt install -y iproute2 # After executing the above command, you can use the command ip addr! root@c0ac350e24fd:/etc/apt# ip addr 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever 8: eth0@if9: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0 inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0 valid_lft forever preferred_lft forever root@c0ac350e24fd:/etc/apt# exit # Let's check the internal address of the container again! [root@iuwza-an ~] docker exec -it tomcat01 ip addr 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever 8: eth0@if9: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0 inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0 valid_lft forever preferred_lft forever # Thinking question: can linux ping through the container? [root@iuwza-an ~]# ping 172.17.0.2 PING 172.17.0.2 (172.17.0.2) 56(84) bytes of data. 64 bytes from 172.17.0.2: icmp_seq=1 ttl=64 time=0.051 ms 64 bytes from 172.17.0.2: icmp_seq=2 ttl=64 time=0.054 ms 64 bytes from 172.17.0.2: icmp_seq=3 ttl=64 time=0.050 ms # linux can ping through the docker container
principle
1. Every time we start a docker container, docker will assign an ip to the docker container. As long as we install docker, there will be a network card docker0
Bridge mode, using evth pair technology!
Test ip addr again
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-WFiB9jUN-1657791393478)(E:\Typora image save location \99.jpg)]
2. Start another container test and find another pair of network cards!
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-N8NWFdiH-1657791393478)(E:\Typora image save location \100.jpg)]
We found that the network cards brought by this container are pair by pair!
Evth pair technology is a pair of virtual device interfaces. They all appear in pairs, one connected to the protocol, the other connected to each other!
Because of this feature, evth pair acts as a bridge connecting various virtual network devices
The connection between OpenStac, Docker containers and OVS uses evth pair technology
3. Let's test whether tomcat01 and tomcat02 can ping!
[root@iuwza-an ~] docker exec -it tomcat01 ping 172.17.0.3 PING 172.17.0.3 (172.17.0.3): 56 data bytes 64 bytes from 172.17.0.3: icmp_seq=0 ttl=64 time=0.112 ms 64 bytes from 172.17.0.3: icmp_seq=1 ttl=64 time=0.087 ms # It is found that it can be ping ed! # Note: if you execute the above command and report the same error as above, install the ping command package in two containers apt install -y inetutils-ping # Conclusion: containers can ping each other!
Network model diagram
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG inanuo1y-1657791393479) (e:\typora image save location \101.jpg)]
Conclusion: tomcat01 and tomcat02 share the same router docker0. When all containers do not specify a network, they are routed by docker0. Docker will assign a default available IP to our containers!
Summary
Docker uses the bridge mode of Linux, and the host is a docker container bridge docker0
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-UuKy9yNq-1657791393479)(E:\Typora image storage location \102.jpg)]
All network interfaces in Docker are virtual, and virtual forwarding efficiency is high! (transfer files via intranet!)
As long as the container is deleted, the corresponding bridge pair will disappear
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG tzcksuqk-1657791393479) (e:\typora image save location \103.jpg)]
31. Docker - link
Thinking scenario: we have written a micro service, database url=ip:, the project does not restart, and the database IP is replaced. We hope to deal with this problem and access the container by name
# You can see that if you fail to pass the --link command 01, you cannot ping 02 [root@iuwza-an ~] docker exec -it tomcat02 ping tomcat01 ping: unknown host # How to solve it? # The problem of network connectivity can be solved through --link [root@iuwza-an ~] docker run -d -P --name tomcat03 --link tomcat02 tomcat 53b824449bac3368793bc47ca9d4dc08428f032c72367920fb26a916e4527727 # Because 03 is new, you also need to install the ping command! [root@iuwza-an ~]# docker exec -it tomcat03 ping tomcat02 OCI runtime exec failed: exec failed: unable to start container process: exec: "ping": executable file not found in $PATH: unknown # You can see the effect of ping [root@iuwza-an ~]# docker exec -it tomcat03 ping tomcat02 PING tomcat02 (172.17.0.3): 56 data bytes 64 bytes from 172.17.0.3: icmp_seq=0 ttl=64 time=0.171 ms 64 bytes from 172.17.0.3: icmp_seq=1 ttl=64 time=0.090 ms 64 bytes from 172.17.0.3: icmp_seq=2 ttl=64 time=0.083 ms # Thinking 03 can ping02, can 02 ping03? [root@iuwza-an ~]# docker exec -it tomcat02 ping tomcat03 ping: unknown host # Check the details of the network [root@iuwza-an ~]# docker network ls NETWORK ID NAME DRIVER SCOPE c71a45bca911 bridge bridge local 6033c6107e30 host host local bd380e17ffd8 none null local [root@iuwza-an ~]# docker network inspect c71a45bca911 [ { "Name": "bridge", "Id": "c71a45bca9116ff689eb6c189e07c9ac4c4b6ee25cee7517083b64aa351f24e6", "Created": "2022-06-05T18:49:56.225697125+08:00", "Scope": "local", "Driver": "bridge", "EnableIPv6": false, "IPAM": { "Driver": "default", "Options": null, "Config": [ { "Subnet": "172.17.0.0/16", "Gateway": "172.17.0.1" } ] }, "Internal": false, "Attachable": false, "Ingress": false, "ConfigFrom": { "Network": "" }, "ConfigOnly": false, "Containers": { "1c3d8bad549d1fb7f26c0731f435f2cf161b5b7434b140780bdbef660f040764": { "Name": "tomcat02", "EndpointID": "422e5767487c4536d6f2ff56dd358d54715bb05fa751ef4dfe02a1346d3fcecc", "MacAddress": "02:42:ac:11:00:03", "IPv4Address": "172.17.0.3/16", "IPv6Address": "" }, "53b824449bac3368793bc47ca9d4dc08428f032c72367920fb26a916e4527727": { "Name": "tomcat03", "EndpointID": "2d996331a04053350ef1fb1ec9abbf5646f412474ecc6deaa2dd5830d79d932e", "MacAddress": "02:42:ac:11:00:04", "IPv4Address": "172.17.0.4/16", "IPv6Address": "" }, "ec8f378007ed16372367ba9b5206fadc508049146d31a06adbcd1ec85007ea0b": { "Name": "tomcat01", "EndpointID": "17a991fa0ad090caa4c848f13cbb9a64a834bbfce5690cac4eac88cec4431b1e", "MacAddress": "02:42:ac:11:00:02", "IPv4Address": "172.17.0.2/16", "IPv6Address": "" } }, "Options": { "com.docker.network.bridge.default_bridge": "true", "com.docker.network.bridge.enable_icc": "true", "com.docker.network.bridge.enable_ip_masquerade": "true", "com.docker.network.bridge.host_binding_ipv4": "0.0.0.0", "com.docker.network.bridge.name": "docker0", "com.docker.network.driver.mtu": "1500" }, "Labels": {} } ]
Inquiry: inspect
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG rtpkcyjl-1657791393479) (e:\typora image save location \104.jpg)]
In fact, tomcat03 is configured with tomcat02 locally
# Principle and essence: you can see that 02 is configured in the hosts configuration file of 03, so you can ping it! [root@iuwza-an ~] docker exec -it tomcat03 cat /etc/hosts 127.0.0.1 localhost ::1 localhost ip6-localhost ip6-loopback fe00::0 ip6-localnet ff00::0 ip6-mcastprefix ff02::1 ip6-allnodes ff02::2 ip6-allrouters 172.17.0.3 tomcat02 1c3d8bad549d 172.17.0.4 53b824449bac
Essence: --link is that we added a 172.17.0.3 tomcat02 1c3d8bad549d mapping configuration in the hosts configuration
It is no longer recommended to use --link with dokcer now
Customize the network! Not applicable to docker0!
docker0 problem: it does not support container name connection access!
32. Docker's custom network
View all docker networks:
[root@iuwza-an ~] docker network ls NETWORK ID NAME DRIVER SCOPE c71a45bca911 bridge bridge local 6033c6107e30 host host local bd380e17ffd8 none null local
Network mode
Bridge: bridge mode docker (default, self created also use bridge mode)
none: do not configure the network
Host: share network with host
Container: container network connectivity! (less use! Very limited)
test
# The command we started directly --net bridge, and this is our docker0 docker run -d -P --name tomcat01 tomcat docker run -d -P --name tomcat01 --net bridge tomcat # docker0 features: by default, the domain name cannot be accessed, -link can get through the connection! # We can customize a network! #View help information [root@iuwza-an ~]# docker network create --help # --driver Bridge (default) # --subnet 192.168.0.0/16 (subnet) # --gateway 192.168.0.1 (Gateway) [root@iuwza-an ~] docker network create --driver bridge --subnet 192.168.0.0/16 --gateway 192.168.0.1 mynet ef2a80a1946f93e4c7689f86934e042cce7663a6c12f36054e5688ec1d04ebd7 [root@iuwza-an ~]# docker network ls NETWORK ID NAME DRIVER SCOPE c71a45bca911 bridge bridge local 6033c6107e30 host host local ef2a80a1946f mynet bridge local bd380e17ffd8 none null local
View the network information created under
[root@iuwza-an ~] docker network inspect mynet [ { "Name": "mynet", "Id": "ef2a80a1946f93e4c7689f86934e042cce7663a6c12f36054e5688ec1d04ebd7", "Created": "2022-06-06T02:12:23.770078164+08:00", "Scope": "local", "Driver": "bridge", "EnableIPv6": false, "IPAM": { "Driver": "default", "Options": {}, "Config": [ { "Subnet": "192.168.0.0/16", "Gateway": "192.168.0.1" } ] }, "Internal": false, "Attachable": false, "Ingress": false, "ConfigFrom": { "Network": "" }, "ConfigOnly": false, "Containers": {}, "Options": {}, "Labels": {} } ]
Test it
# We start two containers [root@iuwza-an ~]# docker run -d -P --name tomcat-net-01 --net mynet tomcat be8355fe9587d1acc834d52510453ee5203e32841abf2d0c6e0641213f890734 [root@iuwza-an ~]# docker run -d -P --name tomcat-net-02 --net mynet tomcat 99bafb55ecff3f1847a87d6d6559516d542db3c0dca081b40c8cb31f602aa842 # Check the information of custom network mynet again [root@iuwza-an ~]# docker network inspect mynet [ { "Name": "mynet", "Id": "ef2a80a1946f93e4c7689f86934e042cce7663a6c12f36054e5688ec1d04ebd7", "Created": "2022-06-06T02:12:23.770078164+08:00", "Scope": "local", "Driver": "bridge", "EnableIPv6": false, "IPAM": { "Driver": "default", "Options": {}, "Config": [ { "Subnet": "192.168.0.0/16", "Gateway": "192.168.0.1" } ] }, "Internal": false, "Attachable": false, "Ingress": false, "ConfigFrom": { "Network": "" }, "ConfigOnly": false, "Containers": { "99bafb55ecff3f1847a87d6d6559516d542db3c0dca081b40c8cb31f602aa842": { "Name": "tomcat-net-02", "EndpointID": "26662112454ebbd448ff257eb20b735113b2dc0277ea5e64658bef89f3b37437", "MacAddress": "02:42:c0:a8:00:03", "IPv4Address": "192.168.0.3/16", "IPv6Address": "" }, "be8355fe9587d1acc834d52510453ee5203e32841abf2d0c6e0641213f890734": { "Name": "tomcat-net-01", "EndpointID": "74ce28ebbde188d403ef56abba3b1b1009dcf92323bc6d9dea543edbc21c474f", "MacAddress": "02:42:c0:a8:00:02", "IPv4Address": "192.168.0.2/16", "IPv6Address": "" } }, "Options": {}, "Labels": {} } ] # Test the ping connection again [root@iuwza-an ~]# docker exec -it tomcat-net-01 ping 192.168.0.3 PING 192.168.0.3 (192.168.0.3): 56 data bytes 64 bytes from 192.168.0.3: icmp_seq=0 ttl=64 time=0.110 ms 64 bytes from 192.168.0.3: icmp_seq=1 ttl=64 time=0.097 ms 64 bytes from 192.168.0.3: icmp_seq=2 ttl=64 time=0.085 ms # Now you can ping the name without --link! [root@iuwza-an ~]# docker exec -it tomcat-net-01 ping tomcat-net-02 PING tomcat-net-02 (192.168.0.3): 56 data bytes 64 bytes from 192.168.0.3: icmp_seq=0 ttl=64 time=0.088 ms 64 bytes from 192.168.0.3: icmp_seq=1 ttl=64 time=0.092 ms 64 bytes from 192.168.0.3: icmp_seq=2 ttl=64 time=0.084 ms 64 bytes from 192.168.0.3: icmp_seq=3 ttl=64 time=0.083 ms
Our customized network docker has helped us maintain the corresponding relationship. It is recommended that we use customized networks at ordinary times!
Benefits:
Because the containers are isolated from each other
redis - different clusters use different networks to ensure that the cluster is safe and healthy
mysql - different clusters use different networks to ensure that the cluster is safe and healthy
33. Docker network connectivity
Hypothetical scenario
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-oM9Z1xbS-1657791393480)(E:\Typora image storage location \105.jpg)]
# Let's start two more containers first [root@iuwza-an ~]# docker run -d -P --name tomcat01 tomcat [root@iuwza-an ~]# docker run -d -P --name tomcat02 tomcat # Can we ping tomcat-net-01 directly with tomcat01 now? [root@iuwza-an ~]# docker exec -it tomcat01 ping tomcat-net-01 ping: unknown host # Don't even think about it now. How can we make it between the two? # solve # Check the help document [root@iuwza-an ~]# docker network --help Usage: docker network COMMAND Manage networks Commands: connect Connect a container to a network # create Create a network disconnect Disconnect a container from a network inspect Display detailed information on one or more networks ls List networks prune Remove all unused networks rm Remove one or more networks # We use the connect option # How to use this option? [root@iuwza-an ~]# docker network connect --help Usage: docker network connect [OPTIONS] NETWORK CONTAINER OPTIONS: Connected objects NETWORK: That network CONTAINER: That container Connect a container to a network Options: --alias strings Add network-scoped alias for the container --driver-opt strings driver options for the network --ip string IPv4 address (e.g., 172.30.100.104) --ip6 string IPv6 address (e.g., 2001:db8::33) --link list Add link to another container --link-local-ip strings Add a link-local address for the container # Test and get through tomcat - mynet [root@iuwza-an ~]# docker network connect mynet tomcat01 # After connecting, tomcat01 is put under the mynet network [root@iuwza-an ~]# docker network inspect mynet [ { "Name": "mynet", "Id": "ef2a80a1946f93e4c7689f86934e042cce7663a6c12f36054e5688ec1d04ebd7", "Created": "2022-06-06T02:12:23.770078164+08:00", "Scope": "local", "Driver": "bridge", "EnableIPv6": false, "IPAM": { "Driver": "default", "Options": {}, "Config": [ { "Subnet": "192.168.0.0/16", "Gateway": "192.168.0.1" } ] }, "Internal": false, "Attachable": false, "Ingress": false, "ConfigFrom": { "Network": "" }, "ConfigOnly": false, "Containers": { "4e706df130e13d9d49fe683fe3716b8b20e26f5147f6cb95c8a9a8c372c284de": { "Name": "tomcat01", "EndpointID": "c365af69b8d9639a06b2642f3ff692184b51c59c7317670116cecc14db5823e0", "MacAddress": "02:42:c0:a8:00:04", "IPv4Address": "192.168.0.4/16", "IPv6Address": "" }, "99bafb55ecff3f1847a87d6d6559516d542db3c0dca081b40c8cb31f602aa842": { "Name": "tomcat-net-02", "EndpointID": "26662112454ebbd448ff257eb20b735113b2dc0277ea5e64658bef89f3b37437", "MacAddress": "02:42:c0:a8:00:03", "IPv4Address": "192.168.0.3/16", "IPv6Address": "" }, "be8355fe9587d1acc834d52510453ee5203e32841abf2d0c6e0641213f890734": { "Name": "tomcat-net-01", "EndpointID": "74ce28ebbde188d403ef56abba3b1b1009dcf92323bc6d9dea543edbc21c474f", "MacAddress": "02:42:c0:a8:00:02", "IPv4Address": "192.168.0.2/16", "IPv6Address": "" } }, "Options": {}, "Labels": {} } ] # One container, two IPS! # Alibaba cloud services: public ip private ip # Test 01 ping [root@iuwza-an ~]# docker exec -it tomcat01 ping tomcat-net-01 PING tomcat-net-01 (192.168.0.2): 56 data bytes 64 bytes from 192.168.0.2: icmp_seq=0 ttl=64 time=0.130 ms 64 bytes from 192.168.0.2: icmp_seq=1 ttl=64 time=0.087 ms # Found that 02 still couldn't get through [root@iuwza-an ~]# docker exec -it tomcat02 ping tomcat-net-01 ping: unknown host
Conclusion: if you want to operate others across the network, you need to use docker network connect to connect
34. Actual combat: deploy Redis cluster
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-WGKCjpGC-1657791393480)(E:\Typora image save location \106.jpg)]
# Create network card docker network create redis --subnet 172.48.0.0/16 # Create six redis configurations through shell script for port in $(seq 1 6); \ do \ mkdir -p /mydata/redis/node-${port}/conf touch /mydata/redis/node-${port}/conf/redis.conf cat <<EOF >/mydata/redis/node-${port}/conf/redis.conf port 6379 bind 0.0.0.0 cluster-enabled yes cluster-config-file nodes.conf cluster-node-timeout 5000 cluster-announce-ip 172.48.0.1${port} cluster-announce-port 6379 cluster-announce-bus-port 16379 appendonly yes EOF done # Use scripts to quickly start six redis for port in $(seq 1 6); \ do \ docker run -p 637${port}:6379 -p 1637${port}:16379 --name redis-1 \ -v /mydata/redis/node-${port}/data:/data \ -v /mydata/redis/node-${port}/conf/redis.conf:/etc/redis/redis.conf \ -d --net redis --ip 172.48.0.${port} redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf done # You can also start one by one manually docker run -p 6371:6379 -p 16371:16379 --name redis-1 \ -v /mydata/redis/node-1/data:/data \ -v /mydata/redis/node-1/conf/redis.conf:/etc/redis/redis.conf \ -d --net redis --ip 172.48.0.11 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf docker run -p 6372:6379 -p 16372:16379 --name redis-2 \ -v /mydata/redis/node-2/data:/data \ -v /mydata/redis/node-2/conf/redis.conf:/etc/redis/redis.conf \ -d --net redis --ip 172.48.0.12 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf docker run -p 6373:6379 -p 16373:16379 --name redis-3 \ -v /mydata/redis/node-3/data:/data \ -v /mydata/redis/node-3/conf/redis.conf:/etc/redis/redis.conf \ -d --net redis --ip 172.48.0.13 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf docker run -p 6374:6379 -p 16374:16379 --name redis-4 \ -v /mydata/redis/node-4/data:/data \ -v /mydata/redis/node-4/conf/redis.conf:/etc/redis/redis.conf \ -d --net redis --ip 172.48.0.14 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf docker run -p 6375:6379 -p 16375:16379 --name redis-5 \ -v /mydata/redis/node-5/data:/data \ -v /mydata/redis/node-5/conf/redis.conf:/etc/redis/redis.conf \ -d --net redis --ip 172.48.0.15 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf docker run -p 6376:6379 -p 16376:16379 --name redis-6 \ -v /mydata/redis/node-6/data:/data \ -v /mydata/redis/node-6/conf/redis.conf:/etc/redis/redis.conf \ -d --net redis --ip 172.48.0.16 redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf # Create cluster #Enter a redis at random first [root@iuwza-an ~]# docker exec -it redis-1 /bin/bash OCI runtime exec failed: exec failed: unable to start container process: exec: "/bin/bash": stat /bin/bash: no such file or directory: unknown # Note: you can see here that there is no bash command by default in redis # Solution: just use sh, which is actually the same. [root@iuwza-an ~]# docker exec -it redis-1 /bin/sh /data # /data redis-cli --cluster create 172.48.0.11:6379 172.48.0.12:6379 172.48.0.13:6379 172.48.0.14:6379 172.48.0.15:6379 172.48.0.16:6379 --cluster-repl icas 1 >>> Performing hash slots allocation on 6 nodes... Master[0] -> Slots 0 - 5460 Master[1] -> Slots 5461 - 10922 Master[2] -> Slots 10923 - 16383 Adding replica 172.48.0.15:6379 to 172.48.0.11:6379 Adding replica 172.48.0.16:6379 to 172.48.0.12:6379 Adding replica 172.48.0.14:6379 to 172.48.0.13:6379 M: 3affc20bfaf036183012c37e209d88c37c5451ee 172.48.0.11:6379 slots:[0-5460] (5461 slots) master M: 3923e874673156702a6d3ea8ac6a4adbdb4297d6 172.48.0.12:6379 slots:[5461-10922] (5462 slots) master M: 7995ab41c4d9d6ba9dc1aaf1ad343192fbd1c138 172.48.0.13:6379 slots:[10923-16383] (5461 slots) master S: 6634b536f67d49d522560727e9ce5a0924988638 172.48.0.14:6379 replicates 7995ab41c4d9d6ba9dc1aaf1ad343192fbd1c138 S: d597aeb1ea474e6d4bdf9ac8b937478306094ef3 172.48.0.15:6379 replicates 3affc20bfaf036183012c37e209d88c37c5451ee S: 8a2274c7f910ab0017d256fb6c900109615d9eb0 172.48.0.16:6379 replicates 3923e874673156702a6d3ea8ac6a4adbdb4297d6 Can I set the above configuration? (type 'yes' to accept): yes #Enter yes here >>> Nodes configuration updated >>> Assign a different config epoch to each node >>> Sending CLUSTER MEET messages to join the cluster Waiting for the cluster to join .... >>> Performing Cluster Check (using node 172.48.0.11:6379) M: 3affc20bfaf036183012c37e209d88c37c5451ee 172.48.0.11:6379 slots:[0-5460] (5461 slots) master 1 additional replica(s) S: 6634b536f67d49d522560727e9ce5a0924988638 172.48.0.14:6379 slots: (0 slots) slave replicates 7995ab41c4d9d6ba9dc1aaf1ad343192fbd1c138 M: 7995ab41c4d9d6ba9dc1aaf1ad343192fbd1c138 172.48.0.13:6379 slots:[10923-16383] (5461 slots) master 1 additional replica(s) S: d597aeb1ea474e6d4bdf9ac8b937478306094ef3 172.48.0.15:6379 slots: (0 slots) slave replicates 3affc20bfaf036183012c37e209d88c37c5451ee S: 8a2274c7f910ab0017d256fb6c900109615d9eb0 172.48.0.16:6379 slots: (0 slots) slave replicates 3923e874673156702a6d3ea8ac6a4adbdb4297d6 M: 3923e874673156702a6d3ea8ac6a4adbdb4297d6 172.48.0.12:6379 slots:[5461-10922] (5462 slots) master 1 additional replica(s) [OK] All nodes agree about slots configuration. >>> Check for open slots... >>> Check slots coverage... [OK] All 16384 slots covered. # You can see that the creation is ok
Enter to check
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-2ZPCUHI6-1657791393481)(E:\Typora image save location \107.jpg)]
Test it
# Let's set the data first 127.0.0.1:6379> set a b -> Redirected to slot [15495] located at 172.48.0.13:6379 OK # You can see that it is processed by redis-3. At this time, redis-3 is a master # Let's stop redis-3 and see if we can get the data of the previous set [root@iuwza-an ~]# docker stop redis-3 redis-3
[the external link image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-8Rr7teWJ-1657791393481)(E:\Typora image save location \108.jpg)]
docker set up the redis cluster!
After we use docker, all technologies will gradually become simpler!
In the future, after we use Docker, we can deliver an image to others!
Here we are, Docker!
n/bash
OCI runtime exec failed: exec failed: unable to start container process: exec: "/bin/bash": stat /bin/bash: no such file or directory: unknown
Note: you can see here that there is no bash command by default in redis
Solution: just use sh, which is actually the same.
[root@iuwza-an ~]# docker exec -it redis-1 /bin/sh
/data #
/data redis-cli --cluster create 172.48.0.11:6379 172.48.0.12:6379 172.48.0.13:6379 172.48.0.14:6379 172.48.0.15:6379 172.48.0.16:6379 --cluster-repl
icas 1
Performing hash slots allocation on 6 nodes...
Master[0] -> Slots 0 - 5460
Master[1] -> Slots 5461 - 10922
Master[2] -> Slots 10923 - 16383
Adding replica 172.48.0.15:6379 to 172.48.0.11:6379
Adding replica 172.48.0.16:6379 to 172.48.0.12:6379
Adding replica 172.48.0.14:6379 to 172.48.0.13:6379
M: 3affc20bfaf036183012c37e209d88c37c5451ee 172.48.0.11:6379
slots:[0-5460] (5461 slots) master
M: 3923e874673156702a6d3ea8ac6a4adbdb4297d6 172.48.0.12:6379
slots:[5461-10922] (5462 slots) master
M: 7995ab41c4d9d6ba9dc1aaf1ad343192fbd1c138 172.48.0.13:6379
slots:[10923-16383] (5461 slots) master
S: 6634b536f67d49d522560727e9ce5a0924988638 172.48.0.14:6379
replicates 7995ab41c4d9d6ba9dc1aaf1ad343192fbd1c138
S: d597aeb1ea474e6d4bdf9ac8b937478306094ef3 172.48.0.15:6379
replicates 3affc20bfaf036183012c37e209d88c37c5451ee
S: 8a2274c7f910ab0017d256fb6c900109615d9eb0 172.48.0.16:6379
replicates 3923e874673156702a6d3ea8ac6a4adbdb4297d6
Can I set the above configuration? (type 'yes' to accept): yes # enter yes here
Nodes configuration updated
Assign a different config epoch to each node
Sending CLUSTER MEET messages to join the cluster
Waiting for the cluster to join
...
Performing Cluster Check (using node 172.48.0.11:6379)
M: 3affc20bfaf036183012c37e209d88c37c5451ee 172.48.0.11:6379
slots:[0-5460] (5461 slots) master
1 additional replica(s)
S: 6634b536f67d49d522560727e9ce5a0924988638 172.48.0.14:6379
slots: (0 slots) slave
replicates 7995ab41c4d9d6ba9dc1aaf1ad343192fbd1c138
M: 7995ab41c4d9d6ba9dc1aaf1ad343192fbd1c138 172.48.0.13:6379
slots:[10923-16383] (5461 slots) master
1 additional replica(s)
S: d597aeb1ea474e6d4bdf9ac8b937478306094ef3 172.48.0.15:6379
slots: (0 slots) slave
replicates 3affc20bfaf036183012c37e209d88c37c5451ee
S: 8a2274c7f910ab0017d256fb6c900109615d9eb0 172.48.0.16:6379
slots: (0 slots) slave
replicates 3923e874673156702a6d3ea8ac6a4adbdb4297d6
M: 3923e874673156702a6d3ea8ac6a4adbdb4297d6 172.48.0.12:6379
slots:[5461-10922] (5462 slots) master
1 additional replica(s)
[OK] All nodes agree about slots configuration.
Check for open slots...
Check slots coverage...
[OK] All 16384 slots covered.
You can see that the creation is ok
Enter to check [External chain pictures are being transferred...(img-2ZPCUHI6-1657791393481)] Test it ```shell # Let's set the data first 127.0.0.1:6379> set a b -> Redirected to slot [15495] located at 172.48.0.13:6379 OK # You can see that it is processed by redis-3. At this time, redis-3 is a master # Let's stop redis-3 and see if we can get the data of the previous set [root@iuwza-an ~]# docker stop redis-3 redis-3
[external chain pictures are being transferred... (img-8Rr7teWJ-1657791393481)]
docker set up the redis cluster!
After we use docker, all technologies will gradually become simpler!
In the future, after we use Docker, we can deliver an image to others!
Here we are, Docker!