一、docker的基本命令
也可以通过docker官网查询docker名:官网->Reference->Command-line Reference
https://docs.docker.com/reference/
#启动docker
systemctl start docker
#关闭docker
systemctl stop docker
#重启docker
systemctl restart docker
#docker设置随服务启动而自启动
systemctl enable docker
#如果是在运行中 输入命令后 会看到绿色的active
systemctl status docker
#查看docker 版本号信息
docker version
docker info
#docker 帮助命令 忘记了某些命令便可使用此进行查看与回顾。比如 咱忘记了 拉取命令 不知道可以带哪些参数 咱可以这样使用
docker --help
docker images --help
二、docker的镜像命令
docker images
[root@iZbp10j4antmyah3ya8nioZ docker]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hello-world latest 9c7a54a9a43c 32 hours ago 13.3kB
查看docker本地库镜像的命令。
默认的docker images将显示所有顶级镜像以及它们的存储库和标签以及它们的大小。
Docker镜像具有中间层,通过允许缓存每个步骤,可以提高可重用性,减少磁盘使用,并加快Docker构建。默认情况下,不会显示这些中间层。
SIZE列表示的是镜像及其所有父镜像占用的累积空间。这也是docker保存镜像时创建的Tar文件的内容所使用的磁盘空间。
如果镜像具有多个存储库名称或标记,则会多次列出该镜像。此单个镜像(可通过其匹配的image ID识别)仅使用一次列出的SIZE。
docker images [OPTIONS] [REPOSITORY[:TAG]]
https://docs.docker.com/engine/reference/commandline/images/
-a, --all Show all images (default hides intermediate images)
--digests Show digests
-f, --filter filter Filter output based on conditions provided
--format string Format output using a custom template:
'table': Print output in table format with column
headers (default)
'table TEMPLATE': Print output in table format using the given
Go template
'json': Print in JSON format
'TEMPLATE': Print output using the given Go template.
Refer to https://docs.docker.com/go/formatting/ for more
information about formatting output with templates
--no-trunc Don't truncate output
-q, --quiet Only show image IDs
docker search
docker search 用于搜索docker hub中的docker镜像。镜像官方地址:https://hub.docker.com/
https://docs.docker.com/engine/reference/commandline/search/
[root@iZbp10j4antmyah3ya8nioZ docker]# docker search --help
Usage: docker search [OPTIONS] TERM
Search Docker Hub for images
Options:
-f, --filter filter Filter output based on conditions provided
--format string Pretty-print search using a Go template
--limit int Max number of search results
--no-trunc Don't truncate output
#mysql 搜索 STARS >9000的 mysql 镜像
docker search --filter=STARS=9000
docker pull
用于拉取镜像,命令文档:https://docs.docker.com/engine/reference/commandline/pull/
[root@iZbp10j4antmyah3ya8nioZ docker]# docker pull --help
Usage: docker pull [OPTIONS] NAME[:TAG|@DIGEST]
Download an image from a registry
Aliases:
docker image pull, docker pull
Options:
-a, --all-tags Download all tagged images in the repository
--disable-content-trust Skip image verification (default true)
--platform string Set platform if server is multi-platform capable
-q, --quiet Suppress verbose output
#docker pull 镜像名
#docker pull 镜像名:tag
#不加tag(版本号) 即拉取docker仓库中 该镜像的最新版本latest 加:tag 则是拉取指定版本
#docker pull mysql
#docker pull mysql:5.7
mysql下载
[root@iZbp10j4antmyah3ya8nioZ docker]# docker pull mysql:5.7
5.7: Pulling from library/mysql
72a69066d2fe: Pull complete #分层下载 docker image的核心 联合文件系统
93619dbc5b36: Pull complete
99da31dd6142: Pull complete
626033c43d70: Pull complete
37d5d7efb64e: Pull complete
ac563158d721: Pull complete
d2ba16033dad: Pull complete
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 pull mysql:5.7
相当于
docker pull docker.io/library/mysql:5.7
docker rm
删除容器
命令地址:https://docs.docker.com/engine/reference/commandline/rm/
# 删除一个容器
docker rm -r 容器id
#删除所有容器
docker rm -f $(docker ps -aq)
docker rmi
删除镜像
命令地址:https://docs.docker.com/engine/reference/commandline/rm/
#删除一个 用镜像名或者镜像id
docker rmi -f 镜像名|镜像ID
#删除多个 其镜像ID或镜像用用空格隔开即可
docker rmi -f 镜像名|镜像ID 镜像名|镜像ID 镜像名|镜像ID
#删除全部镜像 -a 意思为显示全部, -q 意思为只显示ID
docker rmi -f $(docker images -aq)i
5.2、容器的基本命令
docker run
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
命令参考地址:https://docs.docker.com/engine/reference/commandline/run/
作用:Create and run a new container from an image
描述:docker run
命令会在一个新容器里面运行一个命令,如果有需要也会拉取镜像,并启动一个容器。
您可以使用docker start
重新启动一个停止的容器,使其以前的所有更改保持不变。使用docker ps-a
可以查看所有容器的列表,包括那些已停止的容器。
以下是参数的说明:
-i, --interactive
: Keep STDIN(标准输入) open even if not attached。
i的含义是interactive(交互的),意思是即使容器未被链接,也要保持标准输入开启。
-t, --tty
: Allocate a pseudo-TTY,
表示容器启动后会进入其命令行,与i一起使用。分配一个伪tty设备,可以支持终端登录
针对纯操作系统镜像(没有守护进程的)在docker run的时候需要加-it参数,否则启动后会自动退出
-d, --detach
: Run container in background and print container ID
让容器在后台运行并打印容器的ID。如果你的容器启动会打印日志,那边加-d选项在终端就看不到了,需要用docker logs -f 容器ID查看
–privileged=true
:Give extended privileges to this container
授予此容器扩展特权,也就是开启特权模式; 这种模式下容器对docker宿主机拥有root访问权限,允许我们以其宿主机具有(几乎)所有能力来运行容器,包括一些内核特性和设备访问,慎用
–name
:string Assign a name to the container
给容器取一个名字,用docker ps可以查看
–rm
退出容器后,容器会被删除,常用于测试
–hostname
:string Container host name
设置容器里面的主机名,登陆到容器里面可以看到
–restart
:string Restart policy to apply when a container exits (default “no”)
容器退出时的重启策略(4种)
no,默认策略,在容器退出时不重启容器 on-failure,在容器非正常退出时(退出状态非0),才重启容器 on-failure:3,在容器非正常退出时重启容器,最多重启3次 always,在容器退出时总是重启容器 unless-stopped,在容器退出时总是重启容器,如果容器正常stopped,然后机器重启或docker服务重启,容器将不会被restart
更改已运行容器的重启策略
docker update --restart=always test
–network
:string Connect a container to a network (default “default”)
--network可以省略为--net
标准Docker支持4种网络模式
bridge 使用docker daemon指定的网桥,默认为docker0;使用--net=bridge指定,为默认设置 host 容器使用主机的网络 container:NAME_or_ID > 使用其他容器的网络,共享IP和PORT等网络资源 none 容器使用自己的网络,使用--net=none指定
–link
实现通过容器名访问
docker run -d --name test2 --link test1 busybox sleep 3600
test2容器可以直接ping通test1容器名,但test1不能ping通test2容器名
之所以能够Ping通,是因为把
test1的IP地址与容器名、主机名的映射
写入到了test2容器的/etc/hosts文件中
–cpus=1 -m 512M
设置容器CPU和内存的使用上限
-v, --volume
:list Bind mount a volume (default [])
容器与宿主机绑定一个卷
volumes与bind mounts的区别
volumes方式:宿主机有数据时,以宿主机为准;宿主无数据,从容器复制过来,再以宿主机为准 bind方式的宿主机目录会覆盖掉容器中目录的内容(并不删除,只是隐藏)
-v /opt/nginx:/etc/nginx /opt/nginx不存在会自动创建;/opt/nginx会覆盖/etc/nginx目录下的内容
挂载时设置读写权限
挂载时设置读写权限
ro:只读,在容器内只读,只能通过宿主机来操作 rw:读写
docker run -d --name nginx -v /opt/nginx:/opt/test:ro nginx
在容器内不能操作,在容器外可以操作
-w --workdir
:string Working directory inside the container
指定容器的工作目录
-p 80:80
端口映射,前面为宿主机的端口,后面为容器服务进程端口,访问宿主机的80,最终会转发给容器的80端口,实现方式为iptables 注意:如果采用的是–net=host方式,那么不需要做规则转发,可以直接访问
-e, --env
:list Set environment variables (default [])
给容器声明环境变量,在容器内部可以通过export查看
–device
:list Add a host device to the container (default [])
参考文章:https://www.cnblogs.com/vikings-blog/p/4238062.html 默认情况下,container拥有对设备的读,写,创建设备文件的权限。使用:rwm来配合–device,你可以控制这些权限。
docker run --device=/dev/sda:/dev/xvdc --rm
–shm-size
指定shm的大小,默认为64M
--shm-size=200m
–dns 114.114.114.114
手动指定容器内部的DNS
–add-host www.a.com:1.1.1.1
手动往/etc/hosts 文件中注入主机名到 IP 地址的映射
docker.io/nginx:latest
为镜像名:TAG标签,如果不写TAG,默认为latest;也可以用镜像ID来代替
退出容器
exit # 退出容器,且容器停止运行
ctrl+p+q # 退出容器,但是容器不停止运行
docker ps
命令地址:https://docs.docker.com/engine/reference/commandline/ps/
docker ps [OPTIONS]
Name, shorthand | Default | Description |
---|---|---|
--all , -a |
Show all containers (default shows just running) | |
--filter , -f |
Filter output based on conditions provided | |
--format |
Format output using a custom template: ‘table’: Print output in table format with column headers (default) ‘table TEMPLATE’: Print output in table format using the given Go template ‘json’: Print in JSON format ‘TEMPLATE’: Print output using the given Go template. Refer to https://docs.docker.com/go/formatting/ for more information about formatting output with templates | |
--last , -n |
-1 |
Show n last created containers (includes all states) |
--latest , -l |
Show the latest created container (includes all states) | |
--no-trunc |
Don’t truncate output | |
--quiet , -q |
Only display container IDs | |
--size , -s |
Display total file sizes |
容器的停止与启动
# 启动容器
docker start 容器id
#重启容器
docker restart 容器id
#停止容器
docker stop 容器id
#杀死容器
docker kill 容器id
5.3、其他常用命令
后台启动容器
[root@iZbp10j4antmyah3ya8nioZ ~]# docker run -d centos
963b5b4d650890ea944cd04e47d147da0e1842f6c445b270b8d144177ecaa77c
#用docker ps -a 发现没有容器在运行,也就是centos停止了
#常见的坑:docker 容器使用后台运行(-d) ,就必须有一个前台进程。如果没有前台应用,docker发现没有应用,就会自动停止。
#nginx,容器启动后,容器发现自己没有提供服务,就会立即停止。
查看日志命令
$ docker logs [OPTIONS] CONTAINER
Options:
无参数:直接显示容器的所有日志信息 -t, --timestamps :显示时间戳 --tail n:从尾部开始显示n行日志 --since string:从某个时间开始显示容器日志 -f, --follow:将当前时间点,容器日志文件 <container-id>-json.log 中的日志信息全部打印;此时间点之后所有的日志信息与日志文件无关,直接接收goroutine 往日志文件中写的文件描述符,并显示 --details : 显示更多的信息
#以下代码运行centos,并且一直执行一段shell脚本
docker run -d centos /bin/sh -c "while true; do echo hello ; sleep 1;done"
#查看日志
docker logs -tf --tail 10 4950279afd93
查看docker内部进程信息
docker top 容器id
[root@iZbp10j4antmyah3ya8nioZ ~]# docker top 4950279afd93
UID PID PPID C STIME TTY TIME CMD
root 18450 18430 0 20:50 ? 00:00:00 /bin/sh -c while true; do echo hello ; sleep 1;done
root 18935 18450 0 20:56 ? 00:00:00 /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 1
查看容器内部元数据
docker inspect 容器id
[root@iZbp10j4antmyah3ya8nioZ ~]# docker inspect 4950279afd93
[
{
"Id": "4950279afd938b805476fd7985ea6c54fccf8a5b6d58b8ff64fe0bb06df39727",
"Created": "2023-05-06T12:50:24.795412197Z",
"Path": "/bin/sh",
"Args": [
"-c",
"while true; do echo hello ; sleep 1;done"
],
"State": {
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 18450,
"ExitCode": 0,
"Error": "",
"StartedAt": "2023-05-06T12:50:25.013941768Z",
"FinishedAt": "0001-01-01T00:00:00Z"
},
"Image": "sha256:5d0da3dc976460b72c77d94c8a1ad043720b0416bfc16c52c45d4847e53fadb6",
"ResolvConfPath": "/var/lib/docker/containers/4950279afd938b805476fd7985ea6c54fccf8a5b6d58b8ff64fe0bb06df39727/resolv.conf",
"HostnamePath": "/var/lib/docker/containers/4950279afd938b805476fd7985ea6c54fccf8a5b6d58b8ff64fe0bb06df39727/hostname",
"HostsPath": "/var/lib/docker/containers/4950279afd938b805476fd7985ea6c54fccf8a5b6d58b8ff64fe0bb06df39727/hosts",
"LogPath": "/var/lib/docker/containers/4950279afd938b805476fd7985ea6c54fccf8a5b6d58b8ff64fe0bb06df39727/4950279afd938b805476fd7985ea6c54fccf8a5b6d58b8ff64fe0bb06df39727-json.log",
"Name": "/elegant_hoover",
"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,
"ConsoleSize": [
41,
96
],
"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",
"Isolation": "",
"CpuShares": 0,
"Memory": 0,
"NanoCpus": 0,
"CgroupParent": "",
"BlkioWeight": 0,
"BlkioWeightDevice": [],
"BlkioDeviceReadBps": [],
"BlkioDeviceWriteBps": [],
"BlkioDeviceReadIOps": [],
"BlkioDeviceWriteIOps": [],
"CpuPeriod": 0,
"CpuQuota": 0,
"CpuRealtimePeriod": 0,
"CpuRealtimeRuntime": 0,
"CpusetCpus": "",
"CpusetMems": "",
"Devices": [],
"DeviceCgroupRules": null,
"DeviceRequests": null,
"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/98af152e9f8cda2c72c37207b8bde727c867a7c2e0c348a4955971144cbc59ca-init/diff:/var/lib/docker/overlay2/3d0ee0fe5071e657f71aa8e8ff77757a6b7c12be5345db80c1fcea607fe1bee8/diff",
"MergedDir": "/var/lib/docker/overlay2/98af152e9f8cda2c72c37207b8bde727c867a7c2e0c348a4955971144cbc59ca/merged",
"UpperDir": "/var/lib/docker/overlay2/98af152e9f8cda2c72c37207b8bde727c867a7c2e0c348a4955971144cbc59ca/diff",
"WorkDir": "/var/lib/docker/overlay2/98af152e9f8cda2c72c37207b8bde727c867a7c2e0c348a4955971144cbc59ca/work"
},
"Name": "overlay2"
},
"Mounts": [],
"Config": {
"Hostname": "4950279afd93",
"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/sh",
"-c",
"while true; do echo hello ; 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": "57a7fac754ca810c203c5719bb235b3bbb444c9143fa250642fc1b20827a0c6c",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {},
"SandboxKey": "/var/run/docker/netns/57a7fac754ca",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "c16f4d407fe360622dfd2d46f4fc567d0600e57891fbd9e7769b8172c61bdece",
"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": "7d4372ba63eac6f4d94e39c0cb95a32898b026503cf1845391f9e13bbdb361d2",
"EndpointID": "c16f4d407fe360622dfd2d46f4fc567d0600e57891fbd9e7769b8172c61bdece",
"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
[root@iZbp10j4antmyah3ya8nioZ ~]# docker exec --help
Usage: docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
Execute a command in a running container
Aliases:
docker container exec, docker exec
Options:
-d, --detach Detached mode: run command in the background
--detach-keys string Override the key sequence for detaching a container
-e, --env list Set environment variables
--env-file list Read in a file of environment variables
-i, --interactive Keep STDIN open even if not attached
--privileged Give extended privileges to the command
-t, --tty Allocate a pseudo-TTY
-u, --user string Username or UID (format: "<name|uid>[:<group|gid>]")
-w, --workdir string Working directory inside the container
使用示例:
[root@iZbp10j4antmyah3ya8nioZ ~]# docker exec -it 4950279afd93 /bin/bash
[root@4950279afd93 /]# ls
bin etc lib lost+found mnt proc run srv tmp var
dev home lib64 media opt root sbin sys usr
[root@4950279afd93 /]# pwd
/
docker attach
[root@iZbp10j4antmyah3ya8nioZ ~]# docker attach --help
Usage: docker attach [OPTIONS] CONTAINER
Attach local standard input, output, and error streams to a running container
Aliases:
docker container attach, docker attach
Options:
--detach-keys string Override the key sequence for detaching a container
--no-stdin Do not attach STDIN
--sig-proxy Proxy all received signals to the process (default true)
docker exec 进入容器后会开启一个新的终端,可以在里面执行命令操作(常用)
docker attach 进入容器正在执行的终端,不会启动新的终端。
docker cp
命令的帮助文档
[root@iZbp10j4antmyah3ya8nioZ ~]# docker cp --help
Usage: docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH
Copy files/folders between a container and the local filesystem
Use '-' as the source to read a tar archive from stdin
and extract it to a directory destination in a container.
Use '-' as the destination to stream a tar archive of a
container source to stdout.
Aliases:
docker container cp, docker cp
Options:
-a, --archive Archive mode (copy all uid/gid information)
-L, --follow-link Always follow symbol link in SRC_PATH
-q, --quiet Suppress progress output during copy. Progress output is
automatically suppressed if no terminal is attached
docker cp 容器id:/目录/文件名 宿主机目录
[root@iZbp10j4antmyah3ya8nioZ ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d44845f1c6ca centos "/bin/bash" 44 seconds ago Exited (0) 15 seconds ago practical_agnesi
963b5b4d6508 centos "/bin/bash" 58 minutes ago Exited (0) 58 minutes ago charming_golick
8c52c76ed8b3 centos "/bin/bash" About an hour ago Exited (0) About an hour ago nervous_jang
#从容器id为d44845f1c6ca的容器的/root/test.java 文件拷贝到当前目录。
[root@iZbp10j4antmyah3ya8nioZ ~]# docker cp d44845f1c6ca:/root/test.java ./
Successfully copied 1.54kB to /root/./
也可以从把宿主机中的文件拷贝到docker容器内
docker cp ./hello.java d44845f1c6ca:/root/
5.4、docker命令图解
标签:容器,container,--,学习,常用命令,镜像,docker,root From: https://www.cnblogs.com/cplinux/p/17378586.html