Docker基础命令

Docker基础命令

帮助命令

docker version  #版本信息

docker info		#详细信息

docker 命令 --help

镜像命令

[root@ecs-293236 ~]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
hello-world   latest    feb5d9fea6a5   9 months ago   13.3kB
centos        latest    5d0da3dc9764   9 months ago   231MB

#解释
REPOSITORY	镜像的仓库源
TAG			镜像的版本标签
IMAGE ID	镜像的ID
CREATED		镜像创建的时间
SIZE		镜像的大小

#可选项
	[root@ecs-293236 ~]# docker images --help
  -a, --all             列出所有镜像
  -q, --quiet           只显示镜像ID

docker search 搜索镜像

[root@ecs-293236 ~]# docker search mysql
NAME                           DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql                          MySQL is a widely used, open-source relation…   12807     [OK]       
mariadb                        MariaDB Server is a high performing open sou…   4913      [OK]       
percona                        Percona Server is a fork of the MySQL relati…   580       [OK]       
phpmyadmin                     phpMyAdmin - A web interface for MySQL and M…   562       [OK]  

#可选项,过滤搜索
--filter=STARTS=3000  #搜索星星数大于3000的信息
[root@ecs-293236 ~]# docker search mysql --filter=STARS=3000
NAME      DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql     MySQL is a widely used, open-source relation…   12807     [OK]       
mariadb   MariaDB Server is a high performing open sou…   4913      [OK]   

docker pull 下载镜像

# 下载镜像 docker pull 镜像名[:tag]
[root@ecs-293236 ~]# docker pull mysql
Using default tag: latest	#如果不写tag,默认就是latest最新版本
latest: Pulling from library/mysql
72a69066d2fe: Pull complete 	#分层下载,docker images的核心,联合文件系统
93619dbc5b36: Pull complete 
99da31dd6142: Pull complete 
626033c43d70: Pull complete 
37d5d7efb64e: Pull complete 
ac563158d721: Pull complete 
d2ba16033dad: Pull complete 
688ba7d5c01a: Pull complete 
00e060b6d11d: Pull complete 
1c04857f594f: Pull complete 
4d7cfa90e6ea: Pull complete 
e0431212d27d: Pull complete 
Digest: sha256:e9027fe4d91c0153429607251656806cc784e914937271037f7738bd5b8e7709		#签名
Status: Downloaded newer image for mysql:latest
docker.io/library/mysql:latest	#真实地址

#指定版本下载,本地已存在文件不需要重复下载
[root@ecs-293236 ~]# docker pull mysql:5.7
5.7: Pulling from library/mysql
72a69066d2fe: Already exists 
93619dbc5b36: Already exists 
99da31dd6142: Already exists 
626033c43d70: Already exists 
37d5d7efb64e: Already exists 
ac563158d721: Already exists 
d2ba16033dad: Already exists 
0ceb82207cd7: Pull complete 
37f2405cae96: Pull complete 
e2482e017e53: Pull complete 
70deed891d42: Pull complete 
Digest: sha256:f2ad209efe9c67104167fc609cca6973c8422939491c9345270175a300419f94
Status: Downloaded newer image for mysql:5.7
docker.io/library/mysql:5.7

docker rmi 删除镜像

[root@ecs-293236 ~]# docker rmi -f c20987f18b13  #删除5.7版本数据库容器(因有部分资源与最新版本公用,所以删除仅属于5.7的资源)
Untagged: mysql:5.7
Untagged: mysql@sha256:f2ad209efe9c67104167fc609cca6973c8422939491c9345270175a300419f94
Deleted: sha256:c20987f18b130f9d144c9828df630417e2a9523148930dc3963e9d0dab302a76
Deleted: sha256:6567396b065ee734fb2dbb80c8923324a778426dfd01969f091f1ab2d52c7989
Deleted: sha256:0910f12649d514b471f1583a16f672ab67e3d29d9833a15dc2df50dd5536e40f
Deleted: sha256:6682af2fb40555c448b84711c7302d0f86fc716bbe9c7dc7dbd739ef9d757150
Deleted: sha256:5c062c3ac20f576d24454e74781511a5f96739f289edaadf2de934d06e910b92
 
[root@ecs-293236 ~]# docker rmi -f 容器ID		#删除指定的容器
[root@ecs-293236 ~]# docker rmi -f 容器ID	容器ID 容器ID	#删除多个容器
[root@ecs-293236 ~]# docker rmi -f $(docker images -aq)	#删除全部容器

容器命令

说明:有了镜像才可以创建容器
docker pull centos  #下载centos
新建容器并启动
docker run [可选参数] image

#参数说明
--name="NAME" 	容器名字,为容器设置一个名词
-d				后台方式运行
-it				使用交互方式运行,进入容器查看内容
-p				指定容器的端口 -p 8080:8080
	-p 主机端口:容器端口(常用)
	-p 容器端口
	容器端口
-P				随机指定端口

#测试指令,启动并进入容器
[root@ecs-293236 ~]# docker run -it centos /bin/bash
[root@4e863d1f52b4 /]# ls	#查看容器内的centos,系统基础版本,指令不完善
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

#从容器中退回主机
[root@4e863d1f52b4 /]# exit
exit
[root@ecs-293236 ~]# ls
Centos-7.repo

列出所有运行中的容器

# docker ps 命令
		#列出当前正在运行的容器
-a		#列出所有运行过的容器(包括当前正在运行)
-n=? 	#显示最近创建的容器
-q		#只显示容器ID
[root@ecs-293236 ~]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@ecs-293236 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND       CREATED             STATUS                           PORTS     NAMES
4e863d1f52b4   centos         "/bin/bash"   4 minutes ago       Exited (0) About a minute ago              trusting_solomon
23b8cd8786e5   centos         "/bin/bash"   About an hour ago   Exited (0) About an hour ago               exciting_curie
47a68cb71201   centos         "/bin/bash"   About an hour ago   Exited (127) About an hour ago             condescending_meninsky
8a0a0740c900   centos         "/bin/bash"   5 hours ago         Exited (0) 5 hours ago                     elastic_jennings
5f5645327551   feb5d9fea6a5   "/hello"      5 hours ago         Exited (0) 5 hours ago                     loving_sanderson
1ce322f604af   feb5d9fea6a5   "/hello"      4 days ago          Exited (0) 4 days ago                      vigilant_antonelli


退出容器

exit	#直接停止并退出容器
Ctrl + p + q	#容器不停止退出

删除容器

docker rm 容器ID					#删除指定的容器,不能删除正在运行的容器
docker rm -f $(docker ps -aq)	 #删除所有的容器
docker ps -a -q|xargs docker rm  #删除所有的容器

启动和停止容器

docker start 容器ID		#启动容器
docker restart 容器ID		#重启容器
docker stop 容器ID		#停止当前正在运行的容器
docker stop 容器ID		#强制停止当前正在运行的容器

其他常用命令

# 命令 docker run -d 镜像名
[root@ecs-293236 ~]# docker run -d centos
7b6541f268fe3b4ac8b5962081efa66a784ac8b87a0e7773a9b7119339995655
[root@ecs-293236 ~]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@ecs-293236 ~]# 

#问题 docker ps,发现centos停止了
#常见的坑:docker容器使用后台运行,就必须要有一个前台进程,docker发现没有应用,就会自动停止
#nginx,容器启动后,发现自己没有提供服务,就会立刻停止运行

docker logs查看日志

docker logs -f -t --tail 容器,没有日志

#自己编写一段shell脚本
[root@ecs-293236 ~]# docker run -d centos /bin/bash -c "while true;do echo wangkui;sleep 1;done"
520eec1a8a5d80b835c77308de0a0efd06f00595ba42ee2b2388218a5b970a6b
[root@ecs-293236 ~]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS     NAMES
520eec1a8a5d   centos    "/bin/bash -c 'while…"   8 seconds ago   Up 6 seconds             sharp_herschel
[root@ecs-293236 ~]# 

#显示日志
	-tf					#显示日志
	--tail number		#显示指定行数的日志

#显示指定行数的日志
[root@ecs-293236 ~]# docker logs -tf --tail 10 520eec1a8a5d
2022-07-02T09:05:23.270634493Z wangkui
2022-07-02T09:05:24.272410513Z wangkui
2022-07-02T09:05:25.274168902Z wangkui
2022-07-02T09:05:26.275905565Z wangkui
2022-07-02T09:05:27.277846172Z wangkui
2022-07-02T09:05:28.279604263Z wangkui
2022-07-02T09:05:29.281302184Z wangkui
2022-07-02T09:05:30.283109415Z wangkui
2022-07-02T09:05:31.286782268Z wangkui
2022-07-02T09:05:32.286434152Z wangkui
2022-07-02T09:05:33.288182802Z wangkui
2022-07-02T09:05:34.290093794Z wangkui
2022-07-02T09:05:35.291811760Z wangkui
2022-07-02T09:05:36.293471665Z wangkui

查看容器中进程信息

[root@ecs-293236 ~]# docker top 520eec1a8a5d
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                1081272             1081253             0                   17:04               ?                   00:00:00            /bin/bash -c while true;do echo wangkui;sleep 1;done
root                1090432             1081272             0                   17:08               ?                   00:00:00            /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 1

查看镜像元数据

[root@ecs-293236 ~]# docker inspect 520eec1a8a5d
[
    {
        "Id": "520eec1a8a5d80b835c77308de0a0efd06f00595ba42ee2b2388218a5b970a6b",
        "Created": "2022-07-02T09:04:33.88768544Z",
        "Path": "/bin/bash",
        "Args": [
            "-c",
            "while true;do echo wangkui;sleep 1;done"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 1081272,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2022-07-02T09:04:34.185820816Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:5d0da3dc976460b72c77d94c8a1ad043720b0416bfc16c52c45d4847e53fadb6",
        "ResolvConfPath": "/var/lib/docker/containers/520eec1a8a5d80b835c77308de0a0efd06f00595ba42ee2b2388218a5b970a6b/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/520eec1a8a5d80b835c77308de0a0efd06f00595ba42ee2b2388218a5b970a6b/hostname",
        "HostsPath": "/var/lib/docker/containers/520eec1a8a5d80b835c77308de0a0efd06f00595ba42ee2b2388218a5b970a6b/hosts",
        "LogPath": "/var/lib/docker/containers/520eec1a8a5d80b835c77308de0a0efd06f00595ba42ee2b2388218a5b970a6b/520eec1a8a5d80b835c77308de0a0efd06f00595ba42ee2b2388218a5b970a6b-json.log",
        "Name": "/sharp_herschel",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "default",
            "PortBindings": {},
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "CapAdd": null,
            "CapDrop": null,
            "CgroupnsMode": "host",
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "private",
            "Cgroup": "",
            "Links": null,
            "OomScoreAdj": 0,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": null,
            "UTSMode": "",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "runc",
            "ConsoleSize": [
                0,
                0
            ],
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DeviceRequests": null,
            "KernelMemory": 0,
            "KernelMemoryTCP": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": null,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "MaskedPaths": [
                "/proc/asound",
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/e854af8c9a832d6a707622d77b55361566d1413b3c33463472e0e00036d10d4a-init/diff:/var/lib/docker/overlay2/9f2c3298ff8a6c578506a96a234eaa20d47b89c7664e9b0820d41dd6853e7352/diff",
                "MergedDir": "/var/lib/docker/overlay2/e854af8c9a832d6a707622d77b55361566d1413b3c33463472e0e00036d10d4a/merged",
                "UpperDir": "/var/lib/docker/overlay2/e854af8c9a832d6a707622d77b55361566d1413b3c33463472e0e00036d10d4a/diff",
                "WorkDir": "/var/lib/docker/overlay2/e854af8c9a832d6a707622d77b55361566d1413b3c33463472e0e00036d10d4a/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "520eec1a8a5d",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": [
                "/bin/bash",
                "-c",
                "while true;do echo wangkui;sleep 1;done"
            ],
            "Image": "centos",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {
                "org.label-schema.build-date": "20210915",
                "org.label-schema.license": "GPLv2",
                "org.label-schema.name": "CentOS Base Image",
                "org.label-schema.schema-version": "1.0",
                "org.label-schema.vendor": "CentOS"
            }
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "4423ca0f0f6d058b806bed389503b5df4eb6926c814999f6c524926b8483c331",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/4423ca0f0f6d",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "09522ae610a82a8d14558a51fac3f02122e7b51396ff3f047c22ee0398d5ba0c",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.2",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:02",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "3d169d27e1312245ac4f8306173242520d2b4a714ca117241bfb9560d1221a32",
                    "EndpointID": "09522ae610a82a8d14558a51fac3f02122e7b51396ff3f047c22ee0398d5ba0c",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.2",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:02",
                    "DriverOpts": null
                }
            }
        }
    }
]

进入当前正在运行的容器

# 我们通常容器都是使用后台方式运行的,需要进入容器修改一些配置

#命令
docker exec -it 容器ID /bin/bash

#测试
[root@ecs-293236 ~]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS     NAMES
520eec1a8a5d   centos    "/bin/bash -c 'while…"   7 minutes ago   Up 7 minutes             sharp_herschel
[root@ecs-293236 ~]# docker exec -it 520eec1a8a5d /bin/bash
[root@520eec1a8a5d /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[root@520eec1a8a5d /]# ps -ef
UID          PID    PPID  C STIME TTY          TIME CMD
root           1       0  0 09:04 ?        00:00:00 /bin/bash -c while true;do echo wangkui;sleep 1;done
root         532       0  0 09:13 pts/0    00:00:00 /bin/bash
root         552       1  0 09:13 ?        00:00:00 /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 1
root         553     532  0 09:13 pts/0    00:00:00 ps -ef

#方式二
docker attach 容器ID

#区别
# docker exec		#进入容器后开启一个新的终端,可以在里面操作(常用)
# docker attach		#进入容器正在执行的终端,不会启动新的进程

从容器内拷贝文件到主机

docker cp 容器ID:容器内路径 目标主机路径

#查看当前主机目录
[root@ecs-293236 home]# ls
123.java

#进入docker容器内部
[root@ecs-293236 home]# docker attach 84a546f5714a
[root@84a546f5714a /]# cd /home
[root@84a546f5714a home]# ls

#在容器内新建一个文件
[root@84a546f5714a home]# touch test.java
[root@84a546f5714a home]# ls
test.java
[root@84a546f5714a home]# exit
exit
[root@ecs-293236 home]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@ecs-293236 home]# docker ps -a
CONTAINER ID   IMAGE     COMMAND       CREATED         STATUS                      PORTS     NAMES
84a546f5714a   centos    "/bin/bash"   2 minutes ago   Exited (0) 17 seconds ago             vigorous_carver

#将文件拷贝到主机
[root@ecs-293236 home]# docker cp 84a546f5714a:/home/test.java /home
[root@ecs-293236 home]# ls
123.java  test.java

命令总结

attach		Attach to a running container 								#当前sheihiurrach 连接指定运行镜像 
build		Build an image fhom a DockerfHie							#通过 Dockereie 定制镜像 
commit		Create a new image from a container changes					#提出前香器用新的情像
cp			Copyfiles/folders from the containers filesystem to the hos path #从容器中拷贝指定文件或者目 
录到宿主机中
create		Create a new container 							#创建新的咨器,但不启动容器 
diff		Inspect changes on a containens filesysten 		#查着 docke容器变化 
events 		Get real time events from the berve docker 		#服务共取容器实时事件 
exec	 	Run a command in an existing contannen 			#在已存在的容器上运行金今 
export 		Stream the contents of a containel as a tar archive #导出容器的内容流作为一个 tar 归档文件[对应import ]
history 	Show the history of an image 					#展示一个镜像形成历史 
images 		List images 									#列出系统当前镜像 
import 		Create a new filesystem image from the contents of a tarbal1 #从tar色中的内容创建一个新的文件系一统映像[对应export]
info 		Display system-wide information 				#显示系编相关信息 
inspect 	Return 1ow level information on a contine 		#香着容器详细信息 
kin1 		Kill a running container k7k 					#指定ibckep容器 
load 		Load an image from a tar archive 				#从一个 tan 包中加载一个境像t应 save? 
login 		Register or Login to the docker registny server #注册或者喜陆一个ocker 源服务器 
logout 		Log out from a Docker registry server 			#从当前 Dockereaisr 退出
logs 		Fetch the logs of a container 					#输出当前容器日志信息
port 		Lookup the public-facing port which is NATred to PRIVATE PORT #查看映射端口对应的容器内部源端 
pause 		Pause all processes within a contairer! 		#暂停容器
ps 			List containers 								#列出容器列表
pull		Pul1 an image or a repository from the docken registry senver-Mdocker #镜像源服务器拉取指定镜像或者库镜像
push 		Push an image or a repository to the docker registnyseve 	#推送指定镜像或者库镜像至docker源服务器
restart 	Restart a running container 					#重启运行的启器 
rm 			Remove one or more containers 					#移除一个或者多个容器 
rmi 		Remove one or more images 						#移除 个或条个镜像[无容器使用读境像才可删除,否则需删除相关容 器才可继续或f强制删除]
run 		Run a command in a new containe 				#创建一个新的容器并运行一个命令 
save 		Save an image to a tar archive				 	#保存一个镜像为一个 tar 包[对应 load] 
search 		Search for an image on the docker				#在docker hub 中搜索镜像 
start 		Start a stopped contalners 						#启动容器 
stop 		Stop a running containers 						#停止容器 
tag 		Tag an image into a repository 					#给源中镜像打标签 

top			Lookup the running processes of a contatner		#查看容哭中运行的进程信息
unpause	 	Unpause a paused container 						#取消暂停霍器 
version 	Show the docker version information 			#查看 docker 服本号 
wait 		Block unti a container stops then prin!lt exitcode #载取容器停止时的退出状态值 
posted @ 2022-07-02 17:50  昨夜风雨声  阅读(21)  评论(0编辑  收藏  举报  来源