编程知识 cdmana.com

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

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
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
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
d70eaf7277ea
db2b37ec6181
0d120b6ccaa8

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 
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                  PORTS               NAMES
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
f3d143546f7a
[root@192 ~]# docker exec f3 hostname
f3d143546f7a

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 commit [OPTIONS] CONTAINER [REPOSITORY:TAG]
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
https://zhuanlan.zhihu.com/p/152219012

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
https://www.cnblogs.com/ling-yu-amen/p/10955361.html

  • 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
REPOSITORY                              TAG                 IMAGE ID            CREATED              SIZE
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/
abc.txt
-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/
abc.txt
[root@docker ~]# docker run -it --volumes-from $ Containers 1 $ Containers 2 /bin/bash
[root@9b0ca8808591 /]# ls /hello/
abc.txt





–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、Docker-Compose

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
EXPOSE 80
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 :
https://www.cnblogs.com/cag2050/p/10144504.html


[root@192 file]# cat sshd 
FROM centos
MAINTAINER xingyao xingyao.com
RUN yum -y update
RUN yum -y install openssh-server
EXPOSE 22
CMD ["/usr/sbin/sshd", "-D"]
  • Realization Docker-Compose
    Make an application configuration
[root@192 file]# cat docker-compose.yml 
version: '3'
services:
  db:
    image: mariadb
    volumes:
      - /var/lib/docker/disk01:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: password
      MYSQL_USER: centos
      MYSQL_PASSWORD: password
      MYSQL_DATABASE: centos_db
    ports:
      - "3306:3306"
  web:
    build: .
    ports:
      - "80:80"
    volumes:
      - /var/lib/docker/disk02:/var/www/html
  ssh:
    build:
      context: .
      dockerfile: sshd
    ports:
      - "2222:22"
  • Image and container generation
    Close the firewall and selinux
[root@192 file]# docker-compose up -d
[root@192 file]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                NAMES
f4096c00840b        file_web            "/usr/sbin/apachec..."   2 minutes ago       Up 2 minutes        0.0.0.0:80->80/tcp   file_web_1
[root@192 file]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
file_ssh            latest              8a6791c952d6        8 minutes ago       281 MB
file_web            latest              72bf0c7f6dbc        18 minutes ago      285 MB
  • test
# mysql -h 127.0.0.1 -u root -p -e "show variables like 'hostname';"
# mysql -h 127.0.0.1 -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 
 function 
# docker-compose up -d web
6)  Delete application container 
# docker-compose rm

more docker-compose Learning can refer to
https://www.cnblogs.com/minseo/p/11548177.html

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 192.168.135.161 # test machine
    docker 192.168.135.162 # 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 
93395acb90b8636453974921c9742837946b07e02d883f7157f373bdd2078e25
[root@docker ~]# docker ps
CONTAINER ID        IMAGE                          COMMAND                  CREATED             STATUS              PORTS                    NAMES
93395acb90b8        daocloud.io/library/registry   "/entrypoint.sh /e..."   5 minutes ago       Up 5 minutes        0.0.0.0:5000->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 127.0.0.1:5000         // 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 192.168.135.162:5000/busybox    // The host machine ip

[root@client ~]# docker push 192.168.135.162:5000/busybox
The push refers to a repository [192.168.135.162:5000/busybox]
Get https://192.168.135.162:5000/v1/_ping: 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 "192.168.1.100:5000" Request changed to http.

resolvent :

[root@client ~]# touch /etc/docker/daemon.json
[root@client ~]# vim /etc/docker/daemon.json
{ "insecure-registries":["192.168.135.162:5000"] }

[root@client ~]# systemctl restart docker

[root@client ~]# docker push  192.168.135.162:5000/busybox
The push refers to a repository [192.168.135.162:5000/busybox]
8a788232037e: Pushed 
latest: digest: sha256:915f390a8912e16d4beb8689720a17348f3f6d1a7b659697df850ab625ea29d5 size: 527

Look at all the images in the private warehouse

[root@client-161 ~]# curl  192.168.135.162:5000/v2/_catalog
{"repositories":["busybox"]}

View more detailed image information :

[root@client-161 ~]# curl  http://192.168.135.162:5000/v2/busybox/tags/list

The client uses the image of the private repository

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

版权声明
本文为[osc_xsr0bfp3]所创,转载请带上原文链接,感谢

Scroll to Top