[Docker] Docker basic management commands

1. Overview of Docker

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

  • Docker is an open source tool for running applications in Linux containers, a lightweight "virtual machine".

  • Docker's container technology makes it easy to create a lightweight, portable, self-sufficient container for any application on a single host.

  • Docker's logo is designed as a blue whale, dragging many containers.
    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.

  • Docker's design purpose: Build, Ship and Run Any App, Anywhere,
    that is, through the management of the life cycle of application components such as packaging, publishing, deployment, and operation, the purpose of "one-time packaging and running everywhere" at the application component level is achieved. A component here can be an application, a set of services, or even a complete operating system.

1.1 Reasons why containerization is popular

● Flexible: Even the most complex applications can be containerized.
● Lightweight: The container utilizes and shares the host kernel.
● Interchangeable: Updates and upgrades can be deployed instantly.
● Portable: Can be built locally, deployed to the cloud, and run anywhere.
●Extensible: Container replicas can be increased and automatically distributed.
●Stackable: Services can be stacked vertically and instantly.

  • 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 hypervisor, which requires more resources in comparison.

Containers support 2 important technologies in the kernel

  • 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 It does not actually take up 500g of the physical disk, and only copy a copy of the data when it needs to be modified).

The difference between Docker and virtual machine:

the difference container virtual machine
characteristic Docker container virtual machine
startup speed second level minute level
Computing Power Loss almost none About 50% loss
performance close to native weaker than
System support (stand-alone) Thousands tens of
isolation Resource isolation/limitation completely isolated

1.2 Docker Core Concepts

●Mirror
Docker images are the basis for creating containers, similar to virtual machine snapshots, 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.

● Container
Docker's 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 simple version of the Linux environment (including root user authority, mirror space, user space and network space, etc.) and the applications running in it.

●Warehouse
The Docker warehouse is used to centrally save 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.

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

2. Install Docker

Currently Docker only supports 64-bit systems

2.1 Environment preparation

systemctl stop firewalld.service
setenforce 0

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

#设置阿里云镜像源
yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo 

#安装 Docker-CE并设置为开机自动启动
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服务端和客户端运行在一台机器上。
--------------------------------------------------------------------------------------------

#查看 docker 版本信息
docker version

#docker 信息查看
docker info  
Client:
 Context:    default
 Debug Mode: false
 Plugins:
  app: Docker App (Docker Inc., v0.9.1-beta3)
  buildx: Build with BuildKit (Docker Inc., v0.5.1-docker)

Server:
 Containers: 0						# 容器数量
  Running: 0
  Paused: 0
  Stopped: 0
 Images: 1							# 镜像数量
 Server Version: 20.10.3			# server 版本
 Storage Driver: overlay2			# docker 使用的是 overlay2 文件驱动
  Backing Filesystem: xfs			# 宿主机上的底层文件系统
  Supports d_type: true
  Native Overlay Diff: true
 Logging Driver: json-file
 Cgroup Driver: cgroupfs			# Cgroups 驱动
 Cgroup Version: 1
 Plugins:
  Volume: local
  Network: bridge host ipvlan macvlan null overlay
  Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
 Swarm: inactive
 Runtimes: io.containerd.runtime.v1.linux runc io.containerd.runc.v2
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: 269548fa27e0089a8b8278fc4fc781d7f65a939b
 runc version: ff819c7e9184c13b7c2607fe6c30ae19403a7aff
 init version: de40ad0
 Security Options:
  seccomp
   Profile: default
 Kernel Version: 3.10.0-693.el7.x86_64		# 宿主机的相关信息
 Operating System: CentOS Linux 7 (Core)
 OSType: linux
 Architecture: x86_64
 CPUs: 1
 Total Memory: 976.3MiB
 Name: localhost.localdomain
 ID: Y4ES:FTH2:ZJL7:MRVE:RJVB:WJIB:S7BV:C5IZ:LMBR:E4G5:QWSM:SNDT
 Docker Root Dir: /var/lib/docker			# docker 数据存储目录
 Debug Mode: false
 Registry: https://index.docker.io/v1/		# registry 地址
 Labels:
 Experimental: false
 Insecure Registries:
  127.0.0.0/8
 Registry Mirrors:							# 加速站点
  https://xxxxxxxxxx/
 Live Restore Enabled: false


insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

3. Docker image operation

#搜索镜像
格式:docker search 关键字
docker search nginx

#获取镜像
格式:docker pull 仓库名称[:标签]
#如果下载镜像时不指定标签,则默认会下载仓库中最新版本的镜像,即选择标签为 latest 标签。
docker pull nginx

#镜像加速下载
浏览器访问 https://cr.console.aliyun.com/cn-hangzhou/instances/mirrors 获取镜像加速器配置

mkdir -p /etc/docker
tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["https://xxxxxxxxx"]
}
EOF
systemctl daemon-reload
systemctl restart docker

#查看镜像信息
镜像下载后存放在 /var/lib/docker 。
Docker 相关的本地资源存放在 /var/lib/docker/ 目录下,其中 containers 目录存放容器信息,image 目录存放镜像信息,overlay2 目录下存放具体的镜像底层文件。

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

#查看下载到本地的所有镜像
docker images

REPOSITORY   TAG       IMAGE ID       CREATED      SIZE
nginx        latest    ae2feff98a0c   9 days ago   133MB
--------------------------------------------------------------------------------------------
REPOSITORY:镜像属于的仓库;
TAG:镜像的标签信息,标记同一个仓库中的不同镜像;
IMAGE ID:镜像的唯一ID 号,唯一标识一个镜像;
CREATED:镜像创建时间;
VIRTUAL SIZE:镜像大小;
--------------------------------------------------------------------------------------------

#根据镜像的唯一标识 ID 号,获取镜像详细信息
格式:docker inspect 镜像ID号
docker inspect ae2feff98a0c

●lowerdir是镜像层,目录或者文件是只读的,其实就是rootfs,image layer可以分很多层,所以对应的lowerdir是可以有多个目录
●upperdir是在lowerdir之上的容器层,这层是可读可写的,在启动一个容器时候会进行创建,所有的对容器数据更改都发生在这里层
●MergedDir是表现层,是容器的挂载点


#为本地的镜像添加新的标签
格式:docker tag 名称:[标签] 新名称:[新标签]
docker tag nginx:latest nginx:web

docker images | grep nginx

#删除镜像
格式:
docker rmi 仓库名称:标签				#当一个镜像有多个标签时,只是删除其中指定的标签
或者
docker rmi 镜像ID号						#会彻底删除该镜像

注意:如果该镜像已经被容器使用,正确的做法是先删除依赖该镜像的所有容器,再去删除镜像。

docker rmi nginx:web

#存出镜像:将镜像保存成为本地文件
格式:docker save -o 存储文件名 存储的镜像
docker save -o nginx nginx:latest			#存出镜像命名为nginx存在当前目录下
ls -lh

#载入镜像:将镜像文件导入到镜像库中
格式:
docker load < 存出的文件
或者
docker load -i 存出的文件

docker load < nginx

#上传镜像
默认上传到 docker Hub 官方公共仓库,需要注册使用公共仓库的账号。https://hub.docker.com
可以使用 docker login 命令来输入用户名、密码和邮箱来完成注册和登录。
在上传镜像之前,还需要先对本地镜像添加新的标签,然后再使用 docker push 命令进行上传。

docker tag nginx:latest soscscs/nginx:web		#添加新的标签时必须在前面加上自己的dockerhub的username
docker login								#登录公共仓库
Username:soscscs
password:abc123456
docker push soscscs/nginx:web					#上传镜像

Mirror Operation Options

Order Function
search mirror/repository search mirror
pull repository/j image name[:label] get mirror
images View all images downloaded locally
docker inspect image ID number Get image details
tag name: [tag] new name: [new tag] Add a new label to the local mirror
docker rmi warehouse name: label/mirror ID number [-f] delete mirror
docker save -o save filename stored image storage image
docker load -i /> stored files Loading image
docker login Log in to the public repository
docker push soscscs/nginx:web upload mirror

Search mirrors
insert image description here
to obtain mirrors and
insert image description here
mirrors to speed up downloading
insert image description here
insert image description here
insert image description here
View all mirrors downloaded to the local

REPOSITORY: the warehouse to which the image belongs;
TAG: the label information of the image, which marks different images in the same warehouse;
IMAGE ID: the unique ID number of the image, which uniquely identifies an image;
CREATED: the time when the image was created;
VIRTUAL SIZE: the size of the image;

insert image description here

According to the unique identification ID number of the image, get the detailed information of the image

insert image description here

●lowerdir is the image layer, and the directory or file is read-only. In fact, it is rootfs. The image layer can be divided into many layers, so the corresponding lowerdir can have multiple directories. The upperdir is the
container layer above the lowerdir. This layer can Readable and writable, it will be created when a container is started, and all changes to the container data will occur in this layer
MergedDir is the presentation layer, which is the mount point of the container

Add a new label to the local image
insert image description here
Delete the image
insert image description here
insert image description here
Save the image/load the image: save the image as a local file
insert image description here
upload image

insert image description here

4. Docker container operation

#容器创建:就是将镜像加载到容器的过程。
新创建的容器默认处于停止状态,不运行任何程序,需要在其中发起一个进程来启动容器。

格式:docker create [选项] 镜像
常用选项:
-i:让容器开启标准输入接受用户输入命令
-t:让 Docker 分配一个伪终端 tty
-it :合起来实现和容器交互的作用,运行一个交互式会话 shell 

docker create -it nginx:latest /bin/bash

#查看容器的运行状态
docker ps -a			#-a 选项可以显示所有的容器
CONTAINER ID   IMAGE          COMMAND                  CREATED          STATUS    PORTS     NAMES
8b0a7be0ff58   nginx:latest   "/docker-entrypoint.…"   57 seconds ago   Created             inspiring_swanson

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


#启动容器
格式:docker start 容器的ID/名称
docker start 8b0a7be0ff58
docker ps -a

#创建并启动容器
可以直接执行 docker run 命令, 等同于先执行 docker create 命令,再执行 docker start 命令。
注意:容器是一个与其中运行的 shell 命令/进程共存亡的终端,命令/进程运行容器运行, 命令/进程结束容器退出。

docker 容器默认会把容器内部第一个进程,也就是 pid=1 的程序作为docker容器是否正在运行的依据,如果docker容器中 pid = 1 的进程挂了,那么docker容器便会直接退出,也就是说Docker容器中必须有一个前台进程,否则认为容器已经挂掉。


当利用 docker run 来创建容器时, Docker 在后台的标准运行过程是:
(1)检查本地是否存在指定的镜像。当镜像不存在时,会从公有仓库下载;
(2)利用镜像创建并启动一个容器;
(3)分配一个文件系统给容器,在只读的镜像层外面挂载一层可读写层;
(4)从宿主主机配置的网桥接口中桥接一个虚拟机接口到容器中;
(5)分配一个地址池中的 IP 地址给容器;
(6)执行用户指定的应用程序,执行完毕后容器被终止运行。

docker run centos:7 /usr/bin/bash -c ls /
docker ps -a					#会发现创建了一个新容器并启动执行一条 shell 命令,之后就停止了

#在后台持续运行 docker run 创建的容器
需要在 docker run 命令之后添加 -d 选项让 Docker 容器以守护形式在后台运行。并且容器所运行的程序不能结束。

docker run -d centos:7 /usr/bin/bash -c "while true;do echo hello;done"

docker ps -a					#可以看出容器始终处于 UP,运行状态
CONTAINER ID   IMAGE      COMMAND                  CREATED          STATUS         PORTS     NAMES
2592d3fad0fb   centos:7   "/usr/bin/bash -c 'w…"   2 seconds ago    Up 2 seconds             peaceful_chatelet

docker run -itd --name test1 centos:7 /bin/bash   #创建容器并持续运行容器

#终止容器运行
格式:docker stop 容器的ID/名称
docker stop 2592d3fad0fb

docker ps -a

#容器的进入
需要进入容器进行命令操作时,可以使用 docker exec 命令进入运行着的容器。

格式:docker exec -it 容器ID/名称 /bin/bash
-i 选项表示让容器的输入保持打开;
-t 选项表示让 Docker 分配一个伪终端。

docker start 2592d3fad0fb					#进入容器前,确保容器正在运行
docker exec -it 2592d3fad0fb /bin/bash
ls
exit				#退出容器后,容器仍在运行
docker ps -a

docker run -it centos:7 bash      #不加 -d 选项会创建容器后直接进入容器进行交互,但是退出容器,容器也会停止

#复制到容器中
echo abc123 > ~/test.txt
docker cp ~/test.txt 2592d3fad0fb:/opt/

#从容器复制文件到主机
docker cp 2592d3fad0fb:/opt/test.txt ~/abc123.txt

#容器的导出与导入
用户可以将任何一个 Docker 容器从一台机器迁移到另一台机器。在迁移过程中,可以使用docker export 命令将已经创建好的容器导出为容器快照文件,无论这个容器是处于运行状态还是停止状态均可导出。可将导出文件传输到其他机器,通过相应的导入命令实现容器的迁移。

#导出格式:docker export 容器ID/名称 > 文件名
docker export 2592d3fad0fb > centos7.tar

docker export -o centos7.tar 2592d3fad0fb

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

docker import centos7.tar -- centos7:test

#删除容器
格式:docker rm [-f] 容器ID/名称
docker stop 2592d3fad0fb
docker rm 2592d3fad0fb				#删除已经终止状态的容器

docker rm -f 2592d3fad0fb			#强制删除正在运行的容器

docker ps -a | awk 'NR>=2{print "docker stop "$1}' | bash			#批量停止容器
docker ps -a | awk 'NR>=2{print $1}'| xargs docker stop

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

docker images | awk 'NR>=2{print "docker rmi "$3}' | bash			#批量删除镜像
docker images | grep none | awk '{print $3}' | xargs docker rmi		#删除none镜像

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

Container Operations Options

Order Function
docker create -i /t image container creation
docker ps -a View the running status of the container
docker start ID/Name of the container Start the container
docker run -itd --name xxx image sh Create and start the container
docker stop ID/Name of the container Terminate the container
docker exec -it container id/name/bin/bash entry of container
docker cp file location container name/id: location inside the container copied into the container
docker cp container name/ID: the file location where the file location in the container needs to be copied to Copy files from container to host
docker export container id/name > filename to out container
cat filename| docker import -- image name: label Export the file as an image
docker rm [-f] container id/name remove stopped containers -f forcefully remove running containers
docker rm $(docker ps -a -q) Batch clean up the stopped containers in the background

Container creation: It is the process of loading the image into the container.

Format: docker create [option] image
Commonly used options:
-i: let the container open standard input to accept user input commands
-t: let Docker allocate a pseudo-terminal tty
-it: combine to realize the interaction with the container and run an interactive session shell

insert image description here

View the running status of the container

insert image description here
Start the container

insert image description here
Create and start the container

insert image description here
insert image description here
terminate the container run
insert image description here
the entry of the container
insert image description here
copied into the container
insert image description here

copied into the container

insert image description here

Container export and import

insert image description here
delete container

insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/wang_dian1/article/details/131807355
Recommended