Docker basic concepts and deployment and basic commands

foreword

insert image description here

Docker is an open source application container engine that allows developers to package their applications and dependencies into a portable image, and then publish it to any popular Linux or Windows operating system machine, and can also implement virtualization. The container is completely using the sandbox mechanism, and there will be no interface between each other

1. Docker overview

1. The basic concept of docker

  • 1. Is a lightweight "virtual machine", Docker is an open platform for developing, delivering and running applications

  • 2.Docker is an open source application container engine, developed based on the go language and following the apache2.0 protocol open source

  • 3. An open source tool for running applications in Linux containers——"Container Engine, which allows developers to package the applications and dependencies of the gate into a portable image, and then publish them to any popular linux or window machine

  • 4. Docker's container technology can easily create a lightweight, portable, self-sufficient container for any application on a host

  • 5.Docker's logo is designed as a blue whale, dragging many containers

  • 6. The whale can be regarded as a host machine, and the container can be understood as a container isolated from each other, and each container contains its own application

  • 7.Docker's design purpose: Build, Ship and Run Any App, Anywhere (build, publish and allow any application anywhere)

  • 8. That is, through the management of the life cycle of application components such as encapsulation, release, deployment, and operation, the purpose of "encapsulating once and running everywhere" at the application component level is achieved. The components here can be either an application, a set of services, or even a complete operating system

2.docker's sandbox concept

Sandbox : In the field of computer security, a sandbox is an isolated operating mechanism for programs

1. The sandbox is a virtual system program. The environment provided by the sandbox is independent of each running program and will not affect the existing system.

2. To build a test environment, the sandbox application can only access its own application access directory, but cannot share resources between applications, thus forming a relatively safe mechanism, because the sandbox has very good independence and isolation Therefore, some high-risk software can be built for testing, so that application components can be transplanted to services at will after being packaged by Docker

3. Reasons why containerization is becoming more and more popular

  • Flexible: Even the most complex applications can be containerized
  • Lightweight: containers utilize and share the host kernel
  • Interchangeable: Updates and upgrades can be deployed on the fly
  • Portable: Can be built locally, deployed to the cloud, and run anywhere
  • Scalable: container replicas can be increased and automatically distributed
  • Stackable: Serves can be stacked vertically and instantly

4. Why does docker appear

  • As far as linux is concerned, the linux operating system will have a main process pid=1, and other processes are derived to control different services.
    For example: pid=2—python
       pid=3—java
       pid=4—php
    The three services may affect each other
  • Users expect these three different services to run in different runtime environments without affecting each other, and at the same time, it will not increase the cost of the server. It can be extended to package these three services separately, so there is kvm Virtualization technology enables an operating system to simulate multiple operating systems/different runtime environments, and with the development of technology, virtualization technology has a large overhead (for example: as long as you run a py script, you want to use virtualization to achieve it. It is also necessary to install an operating system, which is not convenient/reasonable) From this, the container technology is extended, that is, docker, etc.

5. What is docker

  • docker is a lightweight virtualization solution based on container technology
  • Docker is a container technology that perfectly encapsulates the underlying container technologies such as cgroups and namespaces of linux, and abstracts it to provide users with convenient interfaces for creating and managing containers (command line cli, api, etc.) c/s
  • The essence of docker is a process of the host machine. Docker implements resource isolation through namespace, resource limitation through cgroup, and efficient file operation through copy-on-write technology (similar to virtual machine disks, such as allocating 500g Does not actually take up 500g of physical disk

5.1 Six isolations of namespace

namespace system call parameters quarantine content
UTS CLONE_NEWUTS Hostname and domain name
IPC CLONE_NEWWIPC Semaphores, message queues, and shared memory
PID CLONE_NEWPID process number
NETWORK CLONE_NEWNET Network devices, network stacks, ports, etc.
MOUNT CLONE_NEWNS mount point (filesystem)
USER CLONE_NEWUSER Users and user groups (only supported by kernels after 3.8)

6. What is the point of using docker

  • Achieved three unifications
  • The docker engine unifies the infrastructure environment-docker environment (engine) -- "image --" encapsulates a simple operating system
  • The docker engine unifies the way of program packaging (boxing/encapsulation-analogous to containers)-docker mirroring (put the engine in the mirror and run around with the mirror)—》images
  • The docker engine unifies the way of program deployment (running) - docker container (use the engine to run this image as the same container as before) - "based on the image -" run as a container (runnable environment)
  • Mirror -->> the service/application status at a certain moment of encapsulation
  • Container——>>The state of the application running (the state of normal service provision, runtime)
  • Realized one-time construction, multiple times, and multiple uses
  • Note: The kernel needs to be above 3.8

2. The difference between Docker and virtual machine

  • The container runs natively on Linux and shares the host's kernel with other containers. It runs an independent process and does not occupy the memory of any other executable files. It is very lightweight
  • A virtual machine runs a complete operating system, and virtual access to host resources is performed through a virtual hypervisor, which requires more resources in comparison.
  • Docker solves the problem of an environmental island of vm
  • docker can customize parameter passing (before creating - creating image/container, starting (starting based on image))
characteristic Docker container virtual machine vmware sphere
startup speed Second level (process control) Minute level (guest operating system management)
Computing Power Loss almost none About 50% loss
performance close to native weaker than
System support (stand-alone) hundreds of thousands (processes) Generally dozens of units (operating system level)
isolation Resource isolation/restriction namespace/cgroup (process level) Full isolation system level (more thorough)
operating system Mainly supports Linux (only need to support the engine) Almost all (supported by the host operating system)
disk usage MB GB (OS image 2G)
Encapsulation degree Only package the project code and dependencies, share the host kernel Complete operating system, isolated from the host I

3. The usage scenario of docker

  • The way of K8s image mirror + container container
  • war iar —”aithub aitlab private warehouse (code warehouse)—”jenkins (test)
    (application packaging/build image)—”operation and maintenance download, use container technology to run/publish
  • Packaged Apps for Simple Deployment
  • It can be migrated freely without the underlying hardware (implementing the isolation of applications, splitting and decoupling applications), for example: server migration from Tencent Cloud to Alibaba Cloud
  • Continuous Integration and Delivery (CI/CD): Development to Test Release
  • Deploy microservices
  • Provide PAAS products (Platform as a Service) {OpenStack's cloud host is similar to Alibaba Cloud's Ecs, which belongs to IAAS, Docker (K8s) belongs to PAAS}

Fourth, the core concept of Docker

mirror image A read-only template for the Docker container engine
container A running instance created from an image
storehouse The place where the image is kept in a centralized manner is divided into public warehouses and private warehouses

1. Mirror image

  • The Docker image is the basis for creating a container, similar to a virtual machine snapshot, which can be understood as a read-only template for the Docker container engine

  • Start a container with an image, an executable package that includes everything needed to run an application including code, runtime, libraries, environment variables, and configuration files

  • The Docker image is also a compressed package, but this compressed package is not just an executable file and an environment deployment script, it also contains a complete operating system. Because most of the images are built based on a certain operating system, it is easy to build the same local and remote environment, which is the essence of Docker images

2. Container

  • A Docker container is a running instance created from an image, which can be started, stopped, and deleted. Each container created is isolated and invisible to each other to ensure the security of the platform

  • The container can be regarded as a simplified version of the 1inux environment (including root user authority, mirror space, user space and network space, etc.) and the applications running in it.

    3. Warehouse

  • The Docker warehouse is used to centrally store images. After creating your own image, you can use the push command to upload it to a public warehouse (Public) or a private warehouse (Private). The next time you want to use this image on another machine, just get it from the repository

  • The warehouse is divided into

Public warehouse: Docker official warehouse

Private Warehouse: Personalized and Privatized Warehouse

Docker images, containers, logs, etc. are all stored in the /var/lib/docker directory by default

Summary: Docker is a container management tool. Containers are created from images, images are obtained from warehouses, and warehouses are divided into public and private

Two ways to install Docker on CentOS

  • 1. Use CURL to get the Docker installation script for installation

  • 2. Use the YUM repository to install Docker

5. Docker installation

#目前 Docker 只能支持 64 位系统
#1.关闭防火墙
[root@localhost ~]# systemctl stop firewalld
[root@localhost ~]# systemctl disable firewalld
[root@localhost ~]# setenforce 0

#2.安装依赖包
[root@localhost ~]# yum install -y yum-utils device-mapper-persistent-data lvm2 
##上面依赖环境解释
1.yum-utils:提供了 yum-config-manager 工具
2.device mapper: 是Linux内核中支持逻辑卷管理的通用设备映射机制,它为实现用于存储资源管理的块设备驱动提供了一个高度模块化的内核架构
3.device mapper存储驱动程序需要 device-mapper-persistent-data 和 lvm2
########################################################################

#3.设置阿里云镜像源
[root@localhost ~]# yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo 

#4.安装 Docker-CE 社区版并设置为开机自动启动
[root@localhost ~]# yum install -y docker-ce docker-ce-cli containerd.io
systemctl start docker.service
systemctl enable docker.service 
#安装好的Docker系统有两个程序,Docker.服务端和Docker客户端。其中Docker服务端是个服务进程,负责管理所有容器
#Docker客户端则扮演着Docker.服务端的远程控制器,可以用来控制Docker的服务端进程。大部分情况下Docker服务端和客户揣运行在一·台机器上

#5.查看 docker 版本信息
[root@localhost ~]# docker version  或docker info

1. Aliyun image acceleration

1. Apply for the accelerator address
Here we use the image of Alibaba Cloud to speed up the download speed of the image.
Register an Alibaba Cloud account and log in

insert image description here

Search container mirroring services

insert image description here

View operation document
insert image description here

insert image description here

insert image description here

2. Network optimization

Turning on routing and forwarding allows docker0 to assign virtual ip to all its docker containers according to the virtual machine ip

[root@localhost docker]# vim /etc/sysctl.conf 
[root@localhost docker]# sysctl -p
net.ipv4.ip_forward = 1
[root@localhost docker]# systemctl restart network
[root@localhost docker]# systemctl restart docker
########################################################################
vim /etc/sysctl.conf
net.ipv4.ip_forward=1  #开启路由转发

sysctl -p
systemctl restart network
systemctl restart docker

#####################################################################
#docker-server端配置文件daemon . json
[root@localhost docker]# vim /etc/docker/daemon.json 
{
    
    
"graph" : " / data/docker" ,			#数据目录/var/ lib/docker
"storage-driver" : "overlay2" ,			#存储引擎,早期的时候存储引擎使用的是aufs,现在是overlay2
"insecure-registries": [ "registry.access.redhat.com" , "quary.io"]	#私有仓库
"registry-mirrors" :[ "https :/lq"]		#镜像加速
"bip": "172.17.0.1/24",					#docker网络
"exec-opts" : [ "native.cgroupdriver=systemd" ],	#启动时候的额外参数(驱动,k8s使用)
" live-restore" : true					#当docker容器引擎挂掉的时候,使用docker跑起来的容器还能运行(分离)
}
以上是建议的配置项
docker容器网络生产经验
docker 的网络建议和宿主机的iP"对照”
比如宿主机 10.2.5.6容器的地址就可以修改为172.5.6.1,这样方便在故障发生时,更容易定位故障节点位置


{
  "graph":"/data/docker",
  "storage-driver":"overlay2",
  "insecure-registries":["registry.access.redhat.com","quary.io"],
  "bip":"172.17.0.1/24",
  "exec-opts":["native.cgroupdriver-systemd"],
  "live-restore":true
}
[root@localhost docker]# systemctl daemon-reload
[root@localhost docker]# systemctl restart docke

3. Test docker

[root@nginx1 docker]# docker run hello-world

insert image description here

  • run successfully
  • docker images can see the hello-world just downloaded

insert image description here

6. Basic Docker commands

1. Mirror operation

1.1 View docker version

  • Displays Docker system information, including the number of images and containers
[root@localhost ~]# docker version  或docker info    #显示 Docker 版本信息

insert image description here

1.2 Search mirror

docker search		//从Docker Hub查找镜像
[root@localhost docker]# docker search nginx
NAME	DESCRIPTION	 STARS	OFFICIAL	AUTOMATED

#参数说明:
NAME: 镜像仓库源的名称
DESCRIPTION: 镜像的描述
OFFICIAL: 是否 docker 官方发布
stars: 类似 Github 里面的 star,表示点赞、喜欢的意思
AUTOMATED: 自动构建

1.3 Download mirror

docker pull 	//从镜像仓库中拉取或者更新指定镜像

例:下载nginx
[root@nginx1 docker]# docker pull nginx  #如果下载镜像时不指定标签,则默认会下载仓库中最新版本的镜像,即选择标签为latest标签

1.4 View mirror list

[root@nginx1 docker]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
nginx         latest    605c77e624dd   8 months ago    141MB

#解释
REPOSITORY    //镜像属于的仓库
TAG           //镜像的标签信息,标记同一个仓库中的不同镜像
IMAGE ID      //镜像的唯一ID号,唯一标识一个镜像
CREATED       //镜像创建时间
SIZE          //镜像大小

#选项
-a 				//列出本地所有的镜像(含中间映像层,默认情况下,过滤掉中间映像层)
--digests 		//显示镜像的摘要信息
-f 				//显示满足条件的镜像
--format 		//指定返回值的模板文件
--no-trunc 		//显示完整的镜像信息
-q 				//只显示镜像ID

insert image description here

1.5 View image information

[root@nginx1 docker]# docker inspect nginx    #获取容器,镜像的元数据 或根据镜像的唯一标识ID号,获取镜像详细信息
镜像下载后存放在/var/lib/dodker
Docker相关的本地资源存放在/var/lib/docker/日录下,其中containers
日录存放容器信息,image日录存放镜像信息,overlay2
目录下存放具体的镜像底层文件

#查看下载的镜像文件信息
[root@localhost docker]# cat /var/lib/docker/image/overlay2/repositories.json 

insert image description here

1.6 Add image tag

docker tag 		##标记本地镜像,将其归入某一仓库

#例:
[root@nginx1 docker]# docker tag nginx:latest nginx:q   
[root@nginx1 docker]# docker images   #再次查看发现多出一个镜像
REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
nginx         latest    605c77e624dd   8 months ago    141MB
nginx         q         605c77e624dd   8 months ago    141MB

1.7 Delete mirror

#格式:
docker rmi 镜像名称
docker rmi 镜像标签

#可选项
#注意:如果该镜像已经被容器使用,正确的做法是先删除依赖该镜像的所有容器,再去删除镜像
-f :强制删除

#测试模板
[root@nginx1 docker]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
nginx1        latest    605c77e624dd   8 months ago    141MB
nginx         j         605c77e624dd   8 months ago    141MB
nginx         latest    605c77e624dd   8 months ago    141MB
nginx         q         605c77e624dd   8 months ago    141MB
hello-world   latest    feb5d9fea6a5   11 months ago   13.3kB
  
#例:
[root@nginx1 docker]# docker rmi nginx1 
[root@nginx1 docker]# docker rmi nginx:j
[root@nginx1 docker]# docker rmi -f hello-world:latest 

[root@nginx1 docker]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED        SIZE
nginx        latest    605c77e624dd   8 months ago   141MB
nginx        q         605c77e624dd   8 months ago   141MB

#删除所有:
docker rmi `docker images -q`

#若只想删除centos7
docker rmi `docker images |grep centos:7`

insert image description here

1.8 Image export

#格式:docker save -o	文件名 镜像名	//将指定镜像保存成 tar 归档文件
#选项:
-o :输出到的文件

#例:
[root@nginx1 docker]# docker save -o nginx1 nginx:latest 

insert image description here

1.9 Image import

导入镜像,可以异地导入,但是必须要有docker引擎,并且版本不可以差太多
#格式:docker load < 存出的文件
#可以选项 -i   docker load -i 存出的文件

#例:
[root@nginx1 docker]# docker images  ##查看一下镜像
REPOSITORY   TAG       IMAGE ID       CREATED        SIZE
nginx        latest    605c77e624dd   8 months ago   141MB
nginx        q         605c77e624dd   8 months ago   141MB
[root@nginx1 docker]# docker rmi nginx:latest   #删除原有镜像,测试导入
[root@nginx1 docker]# docker load < nginx1   #导入后再次查看镜像就发现还原了

#也可以将导出的镜像以scp方式导到别的服务器上,然后一样导入测试
[root@nginx1 docker]# pwd
/etc/docker
[root@nginx1 docker]# scp nginx1 192.168.113.127:/opt

insert image description here

1.10 Upload image

By default, it is uploaded to the official public warehouse of docker Hub, and an account that needs to be registered to use the public warehouse https://hub.docker.com

You can use the docker login command to enter the user name, password and email address to complete registration and login

Before uploading the image, you need to add a new label to the local image, and then use the docker push command to upload

docker tag nginx:latest nginx:q		#添加新的标签
[root@nginx1 docker]# docker tag 605c77e624dd qjm1/nginx:q  要改为自己的账户名
[root@nginx1 docker]# docker push qjm1/nginx:q 
[root@nginx1 docker]# docker login    #登录公共仓库
Username: qjm1   #就改为跟他一样的标签
Password: 
[root@nginx1 docker]# docker push qjm1/nginx:q

insert image description here
insert image description here

2. Container Operations

Container creation: the process of loading images into containers

  • The newly created container is in the stopped state by default and does not run any programs. A process needs to be initiated in it to start the container
#新创建的容器默认处于停止状态,不运行任何程序,需要在其中发起一个进程来启动容器。

#格式:docker create [选项] 镜像
#常用选项:
-i:让容器的输入保持打开
-t:让 Docker 分配一个伪终端
-it:合起来实现和容器交互的作用,运行一个交互式会话shell
-d: 让Docker以后台守护进程运行
#示例:
docker create -it nginx:latest /bin/bash

2.1 Query container

[root@nginx1 docker]# docker ps -a  
docker ps -a
--------------------------------------------------------------------------------
CONTAINER ID   IMAGE          COMMAND                  CREATED          STATUS    PORTS     NAMES
8b0a7be0ff58   nginx:latest   "/docker-entrypoint.…"   57 seconds ago   Created             inspiring_swanson

容器的ID号	   加载的镜像     运行的程序               创建时间       当前的状态  端口映射  名称

#可查看容器内进程信息
[root@nginx1 docker]# docker container top 21ff89a79426 
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                11402               11383               0                   20:44               pts/0               00:00:00            /bin/bash

#查看容器的日志信息,-f 为持续监控,-t 为更加详细显示
[root@nginx1 docker]# docker container logs -ft 21ff89a79426
2022-09-05T12:41:55.754558047Z [root@21ff89a79426 /]# eixt
2022-09-05T12:41:55.754625103Z bash: eixt: command not found
2022-09-05T12:42:00.957197185Z [root@21ff89a79426 /]# exit
2022-09-05T12:42:00.957211833Z exit


#选项:
-a :			显示所有的容器,包括未运行的
-f :			根据条件过滤显示的内容
--format :		指定返回值的模板文件
-l :			显示最近创建的容器
-n :			列出最近创建的n个容器
--no-trunc :	不截断输出
-q :			静默模式,只显示容器编号
-s :			显示总的文件大小

2.2 Create container

[root@nginx1 docker]# docker create -it centos:7 /bin/bash #创建一个新的容器但不启动它

#去查询容器会发现状态为Created
[root@nginx1 docker]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                  CREATED              STATUS                   PORTS     NAMES
c5a06d3fefe9   centos:7       "/bin/bash"              About a minute ago   Created         
cranky_franklin


2.3 Start the container and stop

#格式: docker start 容器ID		##启动一个或多个已经被停止的容器
[root@nginx1 docker]# docker start 94aee325884f  #要停止就stop
[root@nginx1 docker]# docker stop 94aee325884f

#例:
#再去查询状态会发现变成正在运行中
[root@nginx1 docker]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                  CREATED         STATUS                   PORTS     NAMES
94aee325884f   nginx:latest   "/docker-entrypoint.…"   8 minutes ago   Up 20 seconds            80/tcp    condescending_shaw

insert image description here

2.4 Start the container (one-time execution)

You can directly execute the docker run command, which is equivalent to executing the docker create command first, and then executing the docker start command

Note: The container is a terminal that coexists with the sel1 command running in it. The command runs and the container runs, and the command ends and the container exits

By default, the docker container will use the first process inside the container, that is, the program with pid=1, as the basis for whether the docker container is running. If the process with pid=1 in the docker container hangs up, the docker container will exit directly, that is, Said that there must be a foreground process in the Docker container, otherwise the container is considered to have hung up

  • When using docker run to create a container, the standard running process of Docker in the background is:

(1) Check whether the specified image exists locally. When the image does not exist, it will be downloaded from the public warehouse
(2) Create and start a container using the image
(3) Assign a file system to the container, mount the read-write layer outside the read-only image layer
(4) From the host The bridge interface configured by the host bridges a virtual machine interface to the container
(5) allocates an IP address in the address pool to the container
(6) executes the application program specified by the user, and the container is terminated after execution

#加 -d 选项让 Docker 容器以守护形式在后台运行。并且容器所运行的程序不能结束

#示例1:
docker run -itd nginx:latest /bin/bash

#示例2:执行后退出
docker run centos:7 /usr/local/bash -c ls /   

#示例3:执行后不退出,以守护进程方式执行持续性任务
docker run -d centos:7 /usr/local/bash -c "while true;do echo hello;done" 

#一次性运行centos:7并查看根
[root@nginx1 docker]# docker run centos:7 /usr/bin/bash -c ls /

#接着去查询状态会发现是退出状态
[root@nginx1 docker]# docker ps -a
CONTAINER ID   IMAGE      COMMAND           CREATED          STATUS                    PORTS     NAMES
6a036e466e1a   centos:7   "/usr/bin/bash"   3 seconds ago    Exited (0) 1 second ago             objective_leakey

#退出状态是因为没有设置守护进程,如果想要他持续运行,需要加上 -d,并给他一个持续性任务
[root@nginx1 docker]# docker run -d centos:7 /bin/bash -c "whice true;do echo hello; done"

#再去查看状态就会是正在运行
[root@nginx1 docker]# docker ps -a
CONTAINER ID   IMAGE      COMMAND                  CREATED          STATUS                       PORTS     NAMES
a28917d35e70   centos:7   "/bin/bash -c 'while…"   4 seconds ago    Up 4 seconds                           dazzling_dijkstra


#创建容器并持续运行容器
[root@nginx1 docker]# docker run -itd --name test1 centos:7 /bin/bash
[root@nginx1 docker]# docker ps
CONTAINER ID   IMAGE          COMMAND                  CREATED             STATUS          PORTS     NAMES
a934133b75e2   centos:7       "/bin/bash"              32 seconds ago      Up 31 seconds             test1
  • options
-a stdin : 	指定标准输入输出内容类型,可选 STDIN/STDOUT/STDERR 三项;

-d : 	后台运行容器,并返回容器ID;

-i : 	以交互模式运行容器,通常与 -t 同时使用;

-P : 	随机端口映射,容器内部端口随机映射到主机的端口

-p :	 指定端口映射,格式为:主机(宿主)端口:容器端口

-t : 	为容器重新分配一个伪输入终端,通常与 -i 同时使用;

--name="nginx-lb" :			 为容器指定一个名称;

--dns 8.8.8.8 :	 			指定容器使用的DNS服务器,默认和宿主一致;

--dns-search example.com :	 指定容器DNS搜索域名,默认和宿主一致;

-h "mars" : 				指定容器的hostname;

-e username="ritchie" : 	设置环境变量;

--env-file=[] : 			从指定文件读入环境变量;

--cpuset="0-2" or --cpuset="0,1,2" : 	绑定容器到指定CPU运行;

-m :						设置容器使用内存最大值;

--net="bridge" : 			指定容器的网络连接类型,支持 bridge/host/none/container : 四种类型;

--link=[] : 				添加链接到另一个容器;

--expose=[] : 				开放一个端口或一组端口;

--volume , -v : 			绑定一个卷

2.5 Entering the container

  • log in with run
[root@nginx1 docker]# docker run -it centos:7 /bin/bash
[root@dc200453a06b /]# 
#若想退出则直接exit,但是容器会自动关闭
[root@nginx1 docker]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                  CREATED              STATUS                        PORTS     NAMES
dc200453a06b   centos:7       "/bin/bash"              About a minute ago   Exited (127) 12 seconds ago             competent_ritchie
  • Use exec (container must be open)
[root@nginx1 docker]# docker start dc200453a06b  
dc200453a06b
[root@nginx1 docker]# docker exec -it dc200453a06b /bin/bash 
[root@dc200453a06b /]# 
  • exec and shell are two modes of operation
  • ps
    ①docker run -it will create a foreground process, but will terminate the process after entering exit
    ②docker attach will connect to the input and output stream in the container by connecting stdin, and will terminate the container process after entering exit
    ③docker exec -it will connect to the container, You can enter the container like SSH and perform operations, and you can exit the container through exit without affecting the running of the container

Copy files from the host (host) to the container

[root@nginx1 docker]# echo 123 > /opt/test.txt
[root@nginx1 docker]# cd /opt
[root@nginx1 opt]# cat test.txt 
123

[root@nginx1 opt]# docker cp /opt/test.txt a934133b75e2:/opt
[root@nginx1 opt]# docker exec -it a934133b75e2 /bin/bash
[root@a934133b75e2 /]# cd /opt
[root@a934133b75e2 opt]# cat test.txt 
123

Copy files from the container to the host (host)

[root@nginx1 opt]# docker exec -it a934133b75e2 /bin/bash
[root@a934133b75e2 /]# cd /opt
[root@a934133b75e2 opt]# echo 456 > /opt/a.txt
[root@a934133b75e2 opt]# cat a.txt 
456
[root@a934133b75e2 opt]# exit

[root@nginx1 opt]# docker cp a934133b75e2:/opt/a.txt /opt/b.txt
[root@nginx1 opt]# cat /opt/b.txt 
456

2.6 Container export

Users can migrate any Docker container from one machine to another. During the migration process, you can use the docker export command to export the created container as a file, regardless of whether the container is running or stopped. The export file can be transferred to other machines, and the migration of the container can be realized through the corresponding import command

#格式:docker export 容器ID > 文件名

#例:
[root@nginx1 docker]# docker export dc200453a06b > centos7-1
[root@nginx1 docker]# ls
centos7-1  daemon.json  key.json  nginx1  文件名

insert image description here

2.7 Container import (generate image)

#格式:docker import 导出的文件名(容器) 指定镜像名称

#例:
[root@nginx1 docker]# docker import centos7-1 centos:7-2
[root@nginx1 docker]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED          SIZE
centos       7-2       5e6e3e6b791e   12 seconds ago   204MB

#方法二
#格式:cat 文件名 | docker import – 镜像名称:标签
cat centos7tar | docker import - centos7:test			#导入后会生成镜像,但不会创建容器

2.8 Delete container

#格式:docker rm 容器ID
#例:
[root@localhost opt]# docker rm adf09d4bda14 

#强制删除容器(正在运行的)
[root@localhost opt]# docker rm -f adf09d4bda14 

#批量删除容器
[root@nginx1 docker]# docker rm `docker ps -aq`



#通过正则匹配批量删除容器
docker ps -a I awk 'NR>=2(print "docker stop "$1)'I bash
#批量停止容器

docker ps -a awk 'NR>=2(print $1}'xargs docker stop
docker ps -a I awk 'NR>=2(print "docker rm "$1)'I bash
#批量删除所有容器

docker ps -a I awk 'NR>=2(print $1}'xargs docker rm
docker images I awk 'NR>=2(print "docker rmi "$3)'I bash
#批量删除镜像

docker images I grep none I awk '(print $3)'I xargs docker rmi
#删除none镜像

docker rm $(docker ps -a -q)
#批量清理后台停止的容器

2.9 Query all current container resource consumption information

[root@nginx1 docker]# docker stats

insert image description here

Failure demonstration docker log is full delete log

#1.创建测试容器
[root@localhost ~]# docker run -itd --name test1 centos:7 /bin/bash

#2.进入容器编写模拟故障脚本
[root@localhost ~]# docker ps
[root@localhost ~]# docker exec -it 4988373fbaa9 /bin/bash
[root@4988373fbaa9 /]# vim 1.sh
#!/bin/bash
i=0
while true
do
let i++
echo "hello world $i"
done
[root@4988373fbaa9 ~]# chmod +x 1.sh
[root@4988373fbaa9 ~]# ./1.sh


#3.查看日志
[root@localhost containers]# pwd
/var/lib/docker/containers
[root@localhost containers]# du -sh *  #此时磁盘空间应该瞬间爆满了

#4.编写脚本删除日志,可以创建周期性任务什么时候执行一次
[root@localhost containers]# vim 2.sh
#!/bin/bash
logs=$(find /var/lib/docker/containers/ -name *-json.log)
for log in logs
do
cat /dev/null > $logecho " " > $log
done
[root@localhost containers]# chmod +x 1.sh
[root@localhost containers]# ./1.sh

#方法二,直接在配置文件里面限制
##设置docker日志文件数量及每个日志大小
 vim /etc/docker/daemon.json
{
    
    
"registry-mirrors": ["http://f613ce8f.m.daocloud.io"]"log-driver": "json-file",
"log-opts": {
    
     "max-size" : "500m", "max-file" : "3"}
}
修改完需要重新加载  
systemctl daemon-reload  
systemctl restart docker

Guess you like

Origin blog.csdn.net/liwenbin19920922/article/details/126903053
Recommended