[docker] basic knowledge, common commands, daily use is enough

osc_xsr0bfp3 2020-11-11 08:33:36
docker basic knowledge common commands

1、docker install

yum Install and start the program

[root@192 ~]# yum install docker -y
[root@192 ~]# systemctl enable docker
[root@192 ~]# systemctl start docker

To configure docker Mirror to accelerate

[root@192 ~]# cat /etc/docker/daemon.json 
"registry-mirrors": ["https://qegs5iwg.mirror.aliyuncs.com"]
[root@192 ~]# systemctl restart docker

Image acceleration acquisition method :
Log in to alicloud ——> product ——> Container services ACK——> Console ——> Container image service ——> The mirror center ——> Image accelerator , According to the prompt , Complete the image acceleration configuration ( Need to sign up )

2、docker Image management

View the current image on the host

[root@192 ~]# docker images
docker.io/ubuntu latest d70eaf7277ea 2 weeks ago 72.9 MB
docker.io/mysql latest db2b37ec6181 2 weeks ago 545 MB
docker.io/centos latest 0d120b6ccaa8 2 months ago 215 MB
[root@192 ~]# docker images -q // Just look at the mirror image of id

Find the image you want to download , And download

[root@192 ~]# docker search all
[root@192 ~]# docker search centos
[root@192 ~]# docker pull docker.io/centos

View image details

[root@192 ~]# docker image inspect $IMAGEID

Change the image name and tag, Equate to Copy a mirror image , Change the name and label
The name of the image is used with the label, with the middle of : for example docker.io/mysql:latest

[root@192 ~]# docker tag $imageid mycentos_nginx:7 
[root@192 ~]#docker tag $REPOSITORY:TAG centos7:ok

delete mirror

# docker image rm daocloud.io/library/mysql // Delete with image name 
# docker rmi ed9c93747fe1 // Use id Delete 
# docker rmi docker.io/ubuntu:latest --force // The image is forced to be deleted in use 
# docker rmi $(docker images -q) // Delete all images 
If the image is being used by a container that is not running , You need to force the deletion of , But if it's being used by a running container , You cannot delete by force

Check out the mirror making process , Equivalent to dockerfile( Later said )

[root@192 ~]# docker image history library/centos
// Make your own mirror image , But it took a long time to complete the mirror , We tend to forget what we did to the mirror , So you can see the history of the mirror . But often we go through dockerfile The way to mirror , Simple and convenient , It's like a script , You can see the record in the script , No need to look at history .

3、docker Container management

Pull up docker Containers

command action Parameters 1、2、3… REPOSITORY shell command
docker run -it docker.io/centos cat /etc/hosts
docker run -it --name mysql /bin/bash
[root@192 ~]# docker run -it --name test docker.io/centos /bin/bash
[root@192 ~]# docker run -it -h $remote_ip/$remote_hostname docker.io/centos /bin/bash
 Parameters, :
-i Capture standard input and output , Keep it interactive 
-t Assign a terminal or console , Every console has to be accompanied by a shell
-d Background running container , And back to ID
-m Set the memory used by the container 
/bin/bash The program that runs after the container runs , It can also be any order .
--name Name the running container 
--dns-search: Specifies the domain to which the container host belongs 
--dns : Appoint dns Server address 
--memory-swap Set up swap 
--cpuset-cpus="1,3" Restricting the use of containers vCPU Of 1 and 3 At the core 
--blkio-weight 600 By default , All containers can read and write disks equally , The default is 500, You can increase the weight to 600
--device-read-bps , Restrict access to a device bps .
--device-write-bps , Restrict writing to a device bps .
--device-read-iops , Restrict access to a device iops .
--device-write-iops , Restrict writing to a device iops
(bps yes byte per second , The amount of data read and written per second ,iops yes io per second , Per second IO The number of times .)
--cidfile: After the specified container runs container Long id The location of the file 
--restart=always: By default docker After restart, all containers will be closed , This option means that the container follows docker engine Self starting .
--rm Delete the container on exit . By default , Each container exits , His file system will survive . On the one hand, it's good for debugging , Because you can determine the final status by looking at the log and so on ; On the other hand , You can also keep the data generated by the container . If you just need to run a container briefly , There is no need to save the data in the container , You can go to exit Automatically clean up the container and its generated data .

Exit the container

[root@432a76428d1d /]#^p^q // Exit the container and continue running 
[root@432a76428d1d /]# exit // after , The container stops working , When you pull it up, add --restart=always The container for the parameter does not stop .

Stop or start the container

[root@192 ~]# docekr stop Containers ID
[root@192 ~]# docekr start Containers ID
//run It's pulling the image up into a container , not run The container that passed ,docker ps -a I can't find out , It's impossible to get through docekr start perhaps docker stop To operate 

Check the running state of the container

[root@192 ~]# docker ps // Containers in operation 
f3d143546f7a docker.io/centos "/bin/bash" 5 seconds ago Up Less than a second serene_sammet
432a76428d1d docker.io/centos "/bin/bash" 11 minutes ago Up 11 minutes loving_tesla
[root@192 ~]# docker ps -a // All the containers pulled up 
[root@192 ~]# docker ps -a -q // View all containers id
[root@192 ~]# docker ps -qf status=running // Look at the container of some state id 

Login container

[root@192 ~]# docker attach $CONTAINERID 
// go back to run State of , Actually log in to the container . perform exit Will exit and stop the container .
[root@192 ~]# docker exec -it $CONTAINERID /bin/bash 
//exec call docker command . perform exit sign out , It doesn't stop the container , You can also add commands directly after
[root@192 ~]# docker exec -it f3 hostname
[root@192 ~]# docker exec f3 hostname

Delete container

[root@192 ~]# docker rm $CONTAINERID
[root@192 ~]# docker rm -f $CONTAINERID // Force deletion of running containers 

View container information / state

[root@192 ~]# docker info // View the information of all containers of the current service 
[root@192 ~]# docker stats $CONTAINERID // see cpu、 Memory 、 disk IO Equal state 
[root@192 ~]# docker inspect $CONTAINERID // View container configuration details , Contains the container name 、 environment variable 、 Run the command 、 Host configuration 、 Network configuration and data volume configuration, etc 
[root@192 ~]# docker logs $CONTAINERID // Check the log 
[root@192 ~]# docker top $CONTAINERID // similar top
[root@192 ~]# docker diff $CONTAINERID // View the changed files in the container ,C Changes in the content of the corresponding file ,A The corresponding are the creation and deletion of files or directories 
[root@192 ~]# docker events // Real time output Docker Server side events , Including the creation of containers , start-up , Shut down, etc .

4、docker Create a custom image

Pull up a container , Deploy the service you want , And then it's packaged into a mirror image , Make sure to use it out of the box next time
commit: Commit container to mirror , Implement container persistence ;
export: Export containers and mirrors , Implement container content persistence ;
save: Export image file , Realize the persistence of mirror content .

4.1、export, Export the running container directly as tar The image file of the package

[root@192 ~]# docker export -o mysql_service.tar $CONTAINERID
[root@192 ~]# docker export $CONTAINERID > 315.tar

Import the image to another server

[root@192 ~]# docker import 315.tar
[root@192 ~]# docker import 315.tar name:7 // The name and tag are added when importing 

4.2、save, Just package the image

[root@192 ~]# docker save -o suibian.tar $REPOSITORY:$TAG

Import the image to another server

[root@192 ~]# docker load < suibian.tar 

4.3、commit, Generate a new image

docker Submit , Generate new version . -m Add notes /-a author /-p,–pause=true Pause container on commit Containers id/name New image name
[root@192 ~]# docker commit -m "ownerimage" -a "centos" 315ed84d3304 hello:v1 

The difference between the above three 、 forehead … There will be gods

4.4、dockerfile, Generate a new image ( The most commonly used )

You can put the command line operations in the configuration file , Create images using configuration files .

  • Get ready Dockerfile file
[root@192 ~]# mkdir /dockerfiletest //docker build You need to specify the directory name 
[root@192 ~]# cd /dockerfiletest
[root@192 dockerfiletest]# touch Dockerfile // Fixed name , Automatically recognize the name when loading 
[root@192 dockerfiletest]# cat Dockerfile 
FROM daocloud.io/library/centos:6
MAINTAINER xingyao xingyao@localhost.localdomain
RUN touch /tmp/a.txt
RUN useradd xingyao
RUN echo 123 |passwd --stdin xingyao
## notes :
FROM  base image , There is direct use of , There is no automatic download 
MAINTAINER  author Author's mailbox 
RUN  Subsequent changes to the mirror image 
RUN  Continue to make changes to the mirror image 
RUN ...
 Every line of command is  INSTRUCTION statement form , I.e. command + The pattern of the manifest .
 Orders should be capitalized 
"#" It's an annotation 
 You can put multiple lines in one line , Use &&  Connect 

More detailed parameters can refer to Daniel's link

  • Use Dockerfile create mirror
[root@192 dockerfiletest]# docker build -t dockerfiletest:v1 . 
-t:tag Is the name of the new image
"." Is used to indicate the use of Dockerfile File current directory , You can also use absolute paths
from Dockerfile The document shows that the whole process is 5 Step , Details of the execution process are displayed on the terminal
[root@192 dockerfiletest]# docker images
dockerfiletest v1 69728f308204 About a minute ago 194 MB

5、docker File sharing between container and host

5.1、docker Between the host and the host copy file

 Containers mysql in /usr/local/bin/ There is docker-entrypoint.sh file , It can be done in the following ways copy To the host
[root@192 ~]# docker cp $ Containers :/usr/local/bin/docker-entrypoint.sh /root
Reset the host file copy Back to the container
[root@192 ~]# docker cp /root/docker-entrypoint.sh $ Containers :/usr/local/bin/ 

5.2、docker The container volume

Using volumes, you can share the host's files into containers , Because it's a shared relationship , So the data in the host directory and the container directory are synchronized . But whether it's a new volume or a volume shared by other containers, it can only be applied to a new container , That is to use volumes when creating containers

New volumes can only be mounted during container creation

[root@docker ~]# docker run -it -v /abc:/hello $ Containers 
[root@docker ~]# touch /abc/abc.txt
[root@71fcb0382357 /]# ls /hello/
-v: Specify a path on the host : Paths in containers . All directories do not need to be created

In practical application, several -v Option to share multiple directories on the host to the new container at the same time :

# docker run -it -v /abc:/abc -v /def:/def $ Containers 

Volumes that share other containers :
[root@docker ~]# docker attach 71
[root@71fcb0382357 /]# ls /hello/
[root@docker ~]# docker run -it --volumes-from $ Containers 1 $ Containers 2 /bin/bash
[root@9b0ca8808591 /]# ls /hello/

–volumes-from: It means that you will 71fc The shared directory in the container is also shared with the new container ,71fc Where to mount the container , The new container is mounted where it is


6.1、docker-compose Introduce

Docker-Compose The project is Docker Official open source projects , Be responsible for the realization of Docker The rapid arrangement of container clusters

  • Docker-Compose Divide the managed containers into three layers :
    engineering ( project )
    service ( service )
    Containers ( container )

  • Docker-Compose Run all the files in the directory ( docker-compose.yml , extends File or environment variable file, etc ) Make a project .
    If there is no special project name, it is the current directory name .
  • A project can contain multiple services , Each service defines the image of the container running , Parameters , rely on .
  • A service can include multiple container instances , Docker-Compose It doesn't solve the problem of load balancing , Therefore, we need to use other tools to realize service discovery and load balancing .
  • Docker-Compose The default project configuration file is docker-compose.yml , Through the environment variable COMPOSE_FILE or -f Parameter custom configuration file , It defines multiple services with dependencies and containers in which each service runs .
  • Use one Dockerfile Template file , It is very convenient for users to define a single application container . At work , It is often encountered that multiple containers need to cooperate with each other to complete a task . For example, to implement a Web project , except Web Service container itself , Often also need to add back-end database service container , It even includes load balancing containers and so on .
  • Compose Allow users to pass through a single docker-compose.yml Template file ( YAML Format ) To define a set of associated application containers as a project ( project ).
  • Docker-Compose Project by Python To write , call Docker service-provided API To manage the container . therefore , As long as the operating platform supports Docker API , You can make use of it Compose To manage the choreography .

6.2、 Realization Docker-Compose

  • install python2-pip And docker-compose
[root@192 ~]# wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
[root@192 ~]# yum --enablerepo=epel -y install python2-pip
[root@192 ~]# pip install docker-compose
  • Write a DockerFile
[root@192 file]# cat Dockerfile 
FROM centos
MAINTAINER xingyao xingyao.com
RUN yum -y update
RUN yum -y install httpd
CMD ["/usr/sbin/apachectl", "-D", "FOREGROUND"]

Why docker function apache To add FOREGROUND?
because Docker The container is only in its 1 Process of no. (PID by 1) Runtime , Will keep running . If 1 No. 1 process has exited ,Docker The container exits .
Reference resources :

[root@192 file]# cat sshd 
FROM centos
MAINTAINER xingyao xingyao.com
RUN yum -y update
RUN yum -y install openssh-server
CMD ["/usr/sbin/sshd", "-D"]
  • Realization Docker-Compose
    Make an application configuration
[root@192 file]# cat docker-compose.yml 
version: '3'
image: mariadb
- /var/lib/docker/disk01:/var/lib/mysql
MYSQL_USER: centos
- "3306:3306"
build: .
- "80:80"
- /var/lib/docker/disk02:/var/www/html
context: .
dockerfile: sshd
- "2222:22"
  • Image and container generation
    Close the firewall and selinux
[root@192 file]# docker-compose up -d
[root@192 file]# docker ps
f4096c00840b file_web "/usr/sbin/apachec..." 2 minutes ago Up 2 minutes>80/tcp file_web_1
[root@192 file]# docker images
file_ssh latest 8a6791c952d6 8 minutes ago 281 MB
file_web latest 72bf0c7f6dbc 18 minutes ago 285 MB
  • test
# mysql -h -u root -p -e "show variables like 'hostname';"
# mysql -h -u centos -p -e "show databases;"
# echo "Hello xingyao" > /var/lib/docker/disk02/index.html
# curl localhost

6.3、 more docker-compose operation

1)  Displays the status of the application container 
# docker-compose ps
2)  Display the application container's  log
# docker-compose logs
3)  Enter the application container 
# docker exec -it root_db_1 /bin/bash
6. docekr-compose  Other operating 
4)  Stop applying containers 
# docker-compose stop
5)  Run an application container  ,  If there are dependent containers, they will also be 
# docker-compose up -d web
6)  Delete application container 
# docker-compose rm

more docker-compose Learning can refer to

7、docker Network type

7.1、 Communication with host

7.1.1、bridge Pattern

  • When Docker When the process starts , A name is created on the host docker0 Virtual bridge , Started on this host Docker The container will be connected to the virtual bridge . Virtual Bridges work like physical switches , This way all the containers on the host are connected to a two-tier network via the switch
  • from docker0 Assign one to a subnet IP Container service , And set up docker0 Of IP The address is the default gateway for the container . Create a pair of virtual network cards on the host veth pair equipment , Docker take veth pair One end of the device is in the newly created container , And named it eth0 ( The network card for the container ), The other end is in the main engine , With vethxxx I'll give it a similar name , And add this network device to it docker0 In the bridge . Can pass brctl show Command view .
  • bridge The pattern is docker The default network mode , Don't write --net Parameters , Namely bridge Pattern . Use docker run -p when , docker It's actually in iptables Did DNAT The rules , Implement port forwarding function . have access to iptables -t nat -vnL see .
# docker run -ti --net=bridge --name c7 centos /bin/bash

 Insert picture description here

7.1.2、host Pattern

If used when starting the container host Pattern , Then the container will not get a separate one Network Namespace , It shares one with the host Network Namespace . The container will not create its own network card , Configure your own IP etc. , It USES the host IP And port . however , Other aspects of the container , Such as file system 、 Process lists and so on are still isolated from the host .

# docker run -ti --net=host --name c7 myimages/centos-ip /bin/bash

 Insert picture description here

7.1.3、Container Pattern

This pattern specifies that the newly created container shares one with an existing one Network Namespace , Instead of sharing it with the host . The newly created container does not create its own network card , Configure your own IP , Instead, it is Shared with a specified container IP 、 Port range, etc . Again , Two containers in addition to the network aspect , Others are file systems 、 Process lists and so on are still isolated . Two container processes can pass through lo Network card device communication .

# docker run -ti --net=bridge --name c7 myimages/centos-ip /bin/bash

 Insert picture description here

7.1.4、None Pattern

Use none Pattern , Docker The container has its own Network Namespace , however , Do not for Docker The container does any network configuration . in other words , This Docker The container has no network card 、 IP 、 Routing information . We need to be ourselves Docker Add network card to container 、 To configure IP etc. .

# docker run -ti --net=none --name c7 myimages/centos-ip /bin/bash

 Insert picture description here

7.2、 Cross-host communication

Look directly at what you have written 、、 That's too much .

8、docekr Private warehouse

  • Environmental preparation
    client # test machine
    docker # Private libraries

  • Implementation steps
    Pull the image of private image warehouse :
[root@docker ~]# docker pull daocloud.io/library/registry
[root@docker ~]# docker images |grep regi
daocloud.io/library/registry latest b2b03e9146e1 3 months ago 33.3 MB
[root@docker ~]# docker run --restart=always -d -p 5000:5000 daocloud.io/library/registry // Port forwarding : Solve the container port access problem  135.161 visit --> The host machine 135.162 Of 5000 port ---> Container of 5000 port 
[root@docker ~]# docker ps
93395acb90b8 daocloud.io/library/registry "/entrypoint.sh /e..." 5 minutes ago Up 5 minutes>5000/tcp naughty_goldwasser

Go into the private warehouse container

[root@docker ~]# docker exec -it 9339 /bin/sh // Here is sh, No bash, No soft connection 
/ # netstat -lnp |grep :5000
tcp 0 0 :::5000 :::* LISTEN 1/registry
/ # 

Access to private warehouses

[root@docker ~]# curl -I // Check the status code as 200
HTTP/1.1 200 OK
Cache-Control: no-cache
Date: Sun, 21 Oct 2018 07:36:11 GMT
Content-Type: text/plain; charset=utf-8

Download Small image buysbox Upload to private library

[root@client ~]# docker pull busybox
[root@client ~]# docker tag busybox // The host machine ip
[root@client ~]# docker push
The push refers to a repository []
Get http: server gave HTTP response to HTTPS client

As shown above, due to the client's adoption of https,docker registry Not used https The service failed to upload successfully "" Request changed to http.

resolvent :

[root@client ~]# touch /etc/docker/daemon.json
[root@client ~]# vim /etc/docker/daemon.json
{ "insecure-registries":[""] }
[root@client ~]# systemctl restart docker
[root@client ~]# docker push
The push refers to a repository []
8a788232037e: Pushed
latest: digest: sha256:915f390a8912e16d4beb8689720a17348f3f6d1a7b659697df850ab625ea29d5 size: 527

Look at all the images in the private warehouse

[root@client-161 ~]# curl

View more detailed image information :

[root@client-161 ~]# curl

The client uses the image of the private repository

[root@client-161 ~]# docker pull
Using default tag: latest
Trying to pull repository ...
latest: Pulling from
90e01955edcd: Pull complete
Digest: sha256:915f390a8912e16d4beb8689720a17348f3f6d1a7b659697df850ab625ea29d5
Status: Downloaded newer image for
[root@client-161 ~]# docker images |grep busy latest 59788edf1f3e 2 weeks ago 1.15 MB

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云