幽沉谢世事,俯默窥唐虞。这篇文章主要讲述docker容器基本操作相关的知识,希望能为你提供帮助。
容器基本操作指令
1、查看镜像
- docker images 可以查看本地镜像
- 格式:
docker images [OPTIONS] [REPOSITORY[:TAG]]
docker image ls [OPTIONS] [REPOSITORY[:TAG]]
#常用选项:
-q, --quiet Only show numeric IDs
-a, --all Show all images (default hides intermediate
--digests Show digests
--no-trunc Dont truncate output
-f, --filter filter Filter output based on conditions provided
--format string Pretty-print images using a Go template
执行结果显示信息说明:
REPOSITORY #镜像所属的仓库名称
TAG #镜像版本号(标识符),默认为latest
IMAGE ID #镜像唯一ID标识,如果ID相同,说明是同一个镜像有多个名称
CREATED #镜像在仓库中被创建时间
VIRTUAL SIZE #镜像的大小
Repository仓库:
- 由某特定的docker镜像的所有迭代版本组成的镜像仓库
- 一个Registry中可以存在多个Repository
- Repository可分为“顶层仓库”和“用户仓库”
- Repository用户仓库名称一般格式为“用户名/仓库名”
- 每个Repository仓库可以包含多个Tag(标签),每个标签对应一个镜像
[root@fsl ~]# docker ps
CONTAINER IDIMAGECOMMANDCREATEDSTATUSPORTSNAMES
4f89226c9cd7centos:centos7.8.2003"/bin/bash"11 minutes agoUp 11 minutescentos
d135d69436f3de6f83bfe0b6"bash"3 months agoUp 3 monthsthirsty_booth#显示完整的imageID
[root@fsl ~]# docker images --no-trunc
REPOSITORYTAGIMAGE IDCREATEDSIZE
ubuntu21.04sha256:de6f83bfe0b632bd4a5018a57a9c0386564d6ece1645862388200d5a81dae9a74 months ago80MB
centoscentos7.8.2003sha256:afb6fca791e071c66276202f8efca5ce3d3dc4fb218bcddff1bc565d981ddd1e21 months ago203MB[root@fsl ~]# docker images -q
de6f83bfe0b6
afb6fca791e0#查看指定镜像的详细信息
[root@fsl ~]# docker inspect 4f89226c9cd7
["Id": "4f89226c9cd7e3c18ea6f49575b2bc7a082b44473b26e8e66ff9103b606a485e",
"Created": "2022-02-10T14:13:25.592445534Z",
"Path": "/bin/bash",
"Args": [],
"State":
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 31155,
"ExitCode": 0,
"Error": "",
"StartedAt": "2022-02-10T14:13:26.878656668Z",
"FinishedAt": "0001-01-01T00:00:00Z"
,
"Image": "sha256:afb6fca791e071c66276202f8efca5ce3d3dc4fb218bcddff1bc565d981ddd1e",
"ResolvConfPath": "/\\"/opt/docker\\"/containers/4f89226c9cd7e3c18ea6f49575b2bc7a082b44473b26e8e66ff9103b606a485e/resolv.conf",
"HostnamePath": "/\\"/opt/docker\\"/containers/4f89226c9cd7e3c18ea6f49575b2bc7a082b44473b26e8e66ff9103b606a485e/hostname",
"HostsPath": "/\\"/opt/docker\\"/containers/4f89226c9cd7e3c18ea6f49575b2bc7a082b44473b26e8e66ff9103b606a485e/hosts",
"LogPath": "/\\"/opt/docker\\"/containers/4f89226c9cd7e3c18ea6f49575b2bc7a082b44473b26e8e66ff9103b606a485e/4f89226c9cd7e3c18ea6f49575b2bc7a082b44473b26e8e66ff9103b606a485e-json.log",
"Name": "/centos",
"RestartCount": 0,
"Driver": "overlay2",
"Platform": "linux",
"MountLabel": "",
"ProcessLabel": "",
"AppArmorProfile": "",
"ExecIDs": null,
"HostConfig":
"Binds": null,
"ContainerIDFile": "",
"LogConfig":
"Type": "json-file",
"Config":
,
"NetworkMode": "host",
"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": "/\\"/opt/docker\\"/overlay2/cd477876416af0c12c0abc5c83d54dcc201d3dc921d35f1bb2d411c85c1aeb0a-init/diff:/\\"/opt/docker\\"/overlay2/98ac8308696fa28f35f47286840e9db4c03aec53bc75a55efc3e14eb352cb2be/diff",
"MergedDir": "/\\"/opt/docker\\"/overlay2/cd477876416af0c12c0abc5c83d54dcc201d3dc921d35f1bb2d411c85c1aeb0a/merged",
"UpperDir": "/\\"/opt/docker\\"/overlay2/cd477876416af0c12c0abc5c83d54dcc201d3dc921d35f1bb2d411c85c1aeb0a/diff",
"WorkDir": "/\\"/opt/docker\\"/overlay2/cd477876416af0c12c0abc5c83d54dcc201d3dc921d35f1bb2d411c85c1aeb0a/work"
,
"Name": "overlay2"
,
"Mounts": [],
"Config":
"Hostname": "fsl",
"Domainname": "",
"User": "",
"AttachStdin": false,
"AttachStdout": false,
"AttachStderr": false,
"Tty": true,
"OpenStdin": true,
"StdinOnce": false,
"Env": [
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
],
"Cmd": [
"/bin/bash"
],
"Image": "centos:centos7.8.2003",
"Volumes": null,
"WorkingDir": "",
"Entrypoint": null,
"OnBuild": null,
"Labels":
"org.label-schema.build-date": "20200504",
"org.label-schema.license": "GPLv2",
"org.label-schema.name": "CentOS Base Image",
"org.label-schema.schema-version": "1.0",
"org.label-schema.vendor": "CentOS",
"org.opencontainers.image.created": "2020-05-04 00:00:00+01:00",
"org.opencontainers.image.licenses": "GPL-2.0-only",
"org.opencontainers.image.title": "CentOS Base Image",
"org.opencontainers.image.vendor": "CentOS",
"NetworkSettings":
"Bridge": "",
"SandboxID": "be5e6738c497ef6e4d54f4c9865667edc5adcd7323bbfbaf7c0b17dbc9b4e07e",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": ,
"SandboxKey": "/var/run/docker/netns/default",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "",
"Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"IPAddress": "",
"IPPrefixLen": 0,
"IPv6Gateway": "",
"MacAddress": "",
"Networks":
"host":
"IPAMConfig": null,
"Links": null,
"Aliases": null,
"NetworkID": "f50d4f7afb074a443302b5c42301f47504f11b3c0e72e17050ec1caac3008dad",
"EndpointID": "db8980fa993ad0f07fc23d12773d2389f93eff4c6bf23e3c3a5cf056fb0e5b84",
"Gateway": "",
"IPAddress": "",
"IPPrefixLen": 0,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "",
"DriverOpts": null]
2、镜像导出
- docker save 命令可以将本地镜像导出为一个打包的tar文件,然后复制到其他服务器进行导入
- 格式:
docker save [OPTIONS] IMAGE [IMAGE...]
选项:
-o, --output string Write to a file, instead of STDOUT
- 常见用法
docker save -o /path/file.tar IMAGE1 IMAGE2 ...
docker save IMAGE1 IMAGE2 ... >
/path/file.tar#可一次导出多个镜像
[root@fsl ~]# docker save centos:centos7.8.2003 ubuntu >
/tmp/all.tar
- 示例:
[root@fsl ~]# docker images
REPOSITORYTAGIMAGE IDCREATEDSIZE
ubuntu21.04de6f83bfe0b64 months ago80MB
centoscentos7.8.2003afb6fca791e021 months ago203MB
[root@fsl ~]# docker save centos:centos7.8.2003 -o /tmp/centos.tar
[root@fsl ~]# ll /tmp/centos.tar
-rw------- 1 root root 211077120 Feb 10 22:46 /tmp/centos.tar
3、镜像导入
- docker load 命令可以将镜像导出的压缩文件再次导入
- 格式:
docker load [OPTIONS]
#选项
-i, --input string Read from tar archive file, instead of STDIN
-q, --quiet Suppress the load output
- 示例:
[root@fsl ~]#docker load -i /tmp/centos.ta
[root@fsl tmp]# docker images
REPOSITORYTAGIMAGE IDCREATEDSIZE
ubuntu21.04de6f83bfe0b64 months ago80MB
centoscentos7.8.2003afb6fca791e021 months ago203MB
4、删除镜像
- docker rmi 命令可以删除本地镜像
- 格式
docker rmi [OPTIONS] IMAGE [IMAGE...]
docker image rm [OPTIONS] IMAGE [IMAGE...]
#选项:
-f, --force Force removal of the image
--no-prune Do not delete untagged parents
- 示例:
[root@fsl tmp]# docker rmi de6f83bfe0b6 强制删除使用-f
Untagged: ubuntu:21.04
Untagged: ubuntu@sha256:cc6f342e3aad515ae49ec9355d852bbba50c3d63e57786438ec36d8989b72f91
Deleted: sha256:de6f83bfe0b632bd4a5018a57a9c0386564d6ece1645862388200d5a81dae9a7
Deleted: sha256:14636cce64eacda8aabad5a94446b86d5e69b7a00d798f4c4bbf920bad3e75ed
[root@fsl tmp]# docker images
REPOSITORYTAGIMAGE IDCREATEDSIZE
centoscentos7.8.2003afb6fca791e021 months ago203MB#删除多个镜像
docker rmi 多个镜像名
#删除所有镜像
docker rmi -f `docker images -q`
5、镜像打标签
- docker tag命令 可以给镜像打标签,类似于起别名
- 格式:
docker tag SOURCE_IMAGE[:TAG] TARGET_IMAGE[:TAG]
#TARGET_IMAGE[:TAG]格式一般形式
仓库主机FQDN或IP[:端口]/项目名(或用户名)/image名字:版本TAG默认为latest
- 示例:
[root@fsl tmp]# docker images
REPOSITORYTAGIMAGE IDCREATEDSIZE
centoscentos7.8.2003afb6fca791e021 months ago203MB
[root@fsl tmp]# docker tag centos:centos7.8.2003 centos:7.8
[root@fsl tmp]# docker images
REPOSITORYTAGIMAGE IDCREATEDSIZE
centos7.8afb6fca791e021 months ago203MB
centoscentos7.8.2003afb6fca791e021 months ago203MB
总结: 企业使用镜像及常见操作: 搜索、下载、导出、导入、删除
6、启动容器
- docker run 可以启动容器,进入到容器,并随机生成容器ID和名称
- 启动容器用法
帮助: man docker-rundocker run [选项] [镜像名] [shell命令] [参数]
#选项:
-i, --interactive Keep STDIN open even if not attached,通常和-t一起使用
-t, --tty 分配pseudo-TTY,通常和-i一起使用,注意对应的容器必须运行shell才支持
进入
-d, --detach Run container in background and print container ID,台后运行,
默认前台
--name string Assign a name to the container
--h, --hostname string Container host name
--rm Automatically remove the container when it exits
-p, --publish list Publish a containers port(s) to the host
-P, --publish-all Publish all exposed ports to random ports
--dns list Set custom DNS servers
--entrypoint string Overwrite the default ENTRYPOINT of the image
--restart policy
--privileged Give extended privileges to container
-e, --env=[] Set environment variables
--env-file=[] Read in a line delimited file of environment variables
- 示例:
[root@fsl tmp]# docker run centos:7.8
[root@fsl tmp]# docker ps -a
CONTAINER IDIMAGECOMMANDCREATEDSTATUSPORTSNAMES
194a6059ac5acentos:7.8"/bin/bash"4 seconds agoExited (0) 3 seconds agohopeful_raman#指定容器名称
[root@fsl tmp]# docker run --name centos1 centos:7.8
[root@fsl tmp]# docker ps -a
CONTAINER IDIMAGECOMMANDCREATEDSTATUSPORTSNAMES
279b5659b879centos:7.8"/bin/bash"5 seconds agoExited (0) 4 seconds agocentos1#运行交互式容器并退出
[root@fsl tmp]# docker run -it centos:7.8 sh
sh-4.2# exit
exit
[root@fsl tmp]#
#用exit退出后容器也停止#设置容器内的主机名
[root@fsl tmp]# docker run -it --name test -h test.baidu.com centos:7.8
[root@test /]# hostname
test.baidu.com
[root@test /]# cat /etc/hosts
127.0.0.1localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.2test.baidu.com test#一次性运行容器,退出后立即删除,用于测试
[root@fsl tmp]# docker run --rm centos:7.8 cat /etc/hosts
什么是守护式容器
- 能够长期运行
- 无需交互会话
- 适合运行应用程序和服务
- 示例:
#启动后台守护式容器[root@fsl tmp]# docker run -itd centos:7.8 bash
a1fd8088073d604222a244ffdcbca78002dc1307d409c3f5134a0fc617b0562c
[root@fsl tmp]# docker ps
CONTAINER IDIMAGECOMMANDCREATEDSTATUSPORTSNAMES
a1fd8088073dcentos:7.8"bash"2 seconds agoUp 1 secondadoring_pasteur# 开机自动运行容器
[root@fsl tmp]# docker run -itd --name centos --restart=alwayscentos:7.8 bash
- --privileged 选项
限。
否则,container内的root只是外部的一个普通用户权限。privileged启动的容器,可以看到很多host上
的设备,并且可以执行mount。甚至允许你在docker容器中启动docker容器。
7、查看容器信息
- 显示当前存在容器
- 格式
docker ps [OPTIONS]
docker container ls [OPTIONS]
选项:
-a, --all Show all containers (default shows just running)
-q, --quiet Only display numeric IDs
-s, --size Display total file sizes
-f, --filter filter Filter output based on conditions provided
-l, --latest Show the latest created container (includes all states)
-n, --last int Show n last created containers (includes all states)
(default -1)
- 示例
#显示运行的容器
[root@fsl tmp]# docker ps
CONTAINER IDIMAGECOMMANDCREATEDSTATUSPORTSNAMES
a1fd8088073dcentos:7.8"bash"3 minutes agoUp 3 minutesadoring_pasteur#显示全部容器,包括退出状态的容器
[root@fsl tmp]# docker ps -a
CONTAINER IDIMAGECOMMANDCREATEDSTATUSPORTSNAMES
a1fd8088073dcentos:7.8"bash"3 minutes agoUp 3 minutesadoring_pasteur
3f2173c727f6centos:7.8"bash"3 minutes agoExited (0) 3 minutes agosharp_driscoll
af992a79a24acentos:7.8"/bin/bash"4 minutes agoExited (0) 4 minutes agodetermined_khorana#只显示容器ID
[root@fsl tmp]# docker ps -a -q
a1fd8088073d
3f2173c727f6
af992a79a24a#显示容器大小
[root@fsl tmp]# docker ps -a -s
CONTAINER IDIMAGECOMMANDCREATEDSTATUSPORTSNAMESSIZE
a1fd8088073dcentos:7.8"bash"3 minutes agoUp 3 minutesadoring_pasteur0B (virtual 203MB)
3f2173c727f6centos:7.8"bash"3 minutes agoExited (0) 3 minutes agosharp_driscoll0B (virtual 203MB)
af992a79a24acentos:7.8"/bin/bash"4 minutes agoExited (0) 4 minutes agodetermined_khorana0B (virtual 203MB)#显示最新创建的容器(停止的容器也能显示)
[root@fsl tmp]# docker ps -a -l#显示指定状态的容器
[root@fsl tmp]# docker ps -f status=exited
CONTAINER IDIMAGECOMMANDCREATEDSTATUSPORTSNAMES
3f2173c727f6centos:7.8"bash"5 minutes agoExited (0) 5 minutes agosharp_driscoll
af992a79a24acentos:7.8"/bin/bash"5 minutes agoExited (0) 5 minutes agodetermined_khorana
- 查看容器内进程
docker top CONTAINER [ps OPTIONS][root@fsl tmp]# docker ps
CONTAINER IDIMAGECOMMANDCREATEDSTATUSPORTSNAMES
a1fd8088073dcentos:7.8"bash"6 minutes agoUp 6 minutesadoring_pasteur
[root@fsl tmp]# docker top a1fd8088073d
UIDPIDPPIDCSTIMETTYTIMECMD
root1109011070023:31pts/000:00:00bash
[root@fsl tmp]#
- 查看容器资源使用情况
docker stats [OPTIONS] [CONTAINER...]
Display a live stream of container(s) resource usage statistics
Options:
-a, --all Show all containers (default shows just running)
--format string Pretty-print images using a Go template
--no-stream Disable streaming stats and only pull the first result
--no-trunc Do not truncate output[root@fsl tmp]# docker stats a1fd8088073dCONTAINER IDNAMECPU %MEM USAGE / LIMITMEM %NET I/OBLOCK I/OPIDS
a1fd8088073dadoring_pasteur0.00%392KiB / 1.795GiB0.02%656B / 0B0B / 0B1CONTAINER IDNAMECPU %MEM USAGE / LIMITMEM %NET I/OBLOCK I/OPIDS
a1fd8088073dadoring_pasteur0.00%392KiB / 1.795GiB0.02%656B / 0B0B / 0B1CONTAINER IDNAMECPU %MEM USAGE / LIMITMEM %NET I/OBLOCK I/OPIDS
a1fd8088073dadoring_pasteur0.00%392KiB / 1.795GiB0.02%656B / 0B0B / 0B1CONTAINER IDNAMECPU %MEM USAGE / LIMITMEM %NET I/OBLOCK I/OPIDS
a1fd8088073dadoring_pasteur0.00%392KiB / 1.795GiB0.02%656B / 0B0B / 0B1
- 查看容器详细信息
- docker inspect 可以查看docker各种对象的详细信息,包括:镜像,容器,网络等
docker inspect [OPTIONS] NAME|ID [NAME|ID...]
Options:
-f, --format string Format the output using the given Go template
-s, --size Display total file sizes if the type is container
- 示例
[root@fsl tmp]# docker inspect a1fd8088073d#选择性查看
[root@fsl tmp]# docker inspect -f ".NetworkSettings" a1fd8088073d
b4798c8e8f132d450e1150b3c9bde81c3ceb4667a2db2b622d04f2c24bb2e2e2 false0 map[] /var/run/docker/netns/b4798c8e8f13 [] [] ccd50d228976d2c90d15d0365c3422f1b595b9235b510b9f77c87d08808574d7 172.17.0.10 172.17.0.2 1602:42:ac:11:00:02 map[bridge:0xc000505b00]
8、删除容器
- docker rm 可以删除容器,即使容器正在运行当中,也可以被强制删除掉
- 格式
docker rm [OPTIONS] CONTAINER [CONTAINER...]
docker container rm [OPTIONS] CONTAINER [CONTAINER...]
#选项:
-f, --force Force the removal of a running container (uses SIGKILL)
-v, --volumes Remove the volumes associated with the container
#删除停止的容器
docker container prune [OPTIONS]
Options:
--filter filter Provide filter values (e.g. until=<
timestamp>
)
-f, --force Do not prompt for confirmation
- 示例
[root@fsl tmp]# docker ps -a
CONTAINER IDIMAGECOMMANDCREATEDSTATUSPORTSNAMES
a1fd8088073dcentos:7.8"bash"14 minutes agoUp 14 minutesadoring_pasteur
3f2173c727f6centos:7.8"bash"14 minutes agoExited (0) 14 minutes agosharp_driscoll
af992a79a24acentos:7.8"/bin/bash"15 minutes agoExited (0) 15 minutes agodetermined_khorana
[root@fsl tmp]# docker rm af992a79a24a
af992a79a24a
[root@fsl tmp]# docker ps -a
CONTAINER IDIMAGECOMMANDCREATEDSTATUSPORTSNAMES
a1fd8088073dcentos:7.8"bash"14 minutes agoUp 14 minutesadoring_pasteur
3f2173c727f6centos:7.8"bash"14 minutes agoExited (0) 14 minutes agosharp_driscoll#删除所有
docker rm -f `docker ps -a -q`#删除指定状态的容器
docker rm `docker ps -qf status=exited`
9、容器启动和停止
- 格式
docker start|stop|restart|pause|unpause 容器ID
- 批量正常启动或关闭所有容器
docker start $(docker ps -a -q)
docker stop $(docker ps -a -q)
- docker kill 可以给容器发信号,默认号SIGKILL,即9信号
- 格式
docker kill [OPTIONS] CONTAINER [CONTAINER...]
#选项:
s, --signal string Signal to send to the container (default "KILL")
10、进入容器
- 使用exec命令
- 在运行中的容器启动新进程,可以执行单次命令,以及进入容器测试环境使用此方式,使用exit退出,但容器还在运行,此为推荐方式
- 格式:
docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
常用选项:
-d, --detach Detached mode: run command in the background
-e, --env list Set environment variables
-i, --interactive Keep STDIN open even if not attached
-t, --tty Allocate a pseudo-TTY
#常见用法
docker exec -it 容器ID sh|bash
- 示例
[root@fsl tmp]# docker exec -it a1fd8088073d bash
[root@a1fd8088073d /]# cat /etc/redhat-release
CentOS Linux release 7.8.2003 (Core)
[root@a1fd8088073d /]# exit
exit
[root@fsl tmp]# docker ps
CONTAINER IDIMAGECOMMANDCREATEDSTATUSPORTSNAMES
a1fd8088073dcentos:7.8"bash"19 minutes agoUp 19 minutesadoring_pasteur
- 脚本方式
cat docker-in.sh
#!/bin/bash
docker_in()
NAME_ID=$1
PID=$(docker inspect -f ".State.Pid" $NAME_ID)
nsenter -t $PID -m -u -i -n -pdocker_in $1
11、 暴露所有容器端口
- docker run -P 可以将事先容器预定义的所有端口映射宿主机的网卡的随机端口,默认从32768开始
- 使用随机端口 时,当停止容器后再启动可能会导致端口发生变化
- 格式
-P , --publish-all= true | false默认为false
#示例:
docker run -P docker.io/nginx #映射容器所有暴露端口至随机本地端口
- docker port 可以查看容器的端口映射关系
- 格式
docker port CONTAINER [PRIVATE_PORT[/PROTO]]
- 示例
[root@fsl tmp]# docker port a1fd8088073d
12、 指定端口映射
- docker run -p 可以将容器的预定义的指定端口映射到宿主机的相应端口
- 注意: 多个容器映射到宿主机的端口不能冲突,但容器内使用的端口可以相同
- 方式
#方式一 容器80端口映射宿主机本地随机端口
[root@fsl tmp]#docker run -p 80 --name centos a1fd8088073d#方式2: 容器80端口映射到宿主机本地端口81
[root@fsl tmp]#docker run -p 81:80 --name centos a1fd8088073d#方式3: 宿主机本地IP:宿主机本地端口:容器端口
[root@fsl tmp]#docker run -p 10.0.0.100:82:80 --name centos a1fd8088073d#方式4: 宿主机本地IP:宿主机本地随机端口:容器端口,默认从32768开始
[root@fsl tmp]#docker run -p 10.0.0.100::80 --name centos a1fd8088073d#方式5: 宿主机本机ip:宿主机本地端口:容器端口/协议,默认为tcp协议
[root@fsl tmp]#docker run -p 10.0.0.100:83:80/udp --name centos a1fd8088073d#方式6: 一次性映射多个端口+协议
[root@fsl tmp]#docker run -p 8080:80/tcp -p 8443:443/tcp -p 53:53/udp --name centos a1fd8088073d
- 修改已经创建的容器端口映射关系
[root@ubuntu1804 ~]#docker run -d -p 80:80 --name nginx01 nginx
dc5d7c1029e582a3e05890fd18565367482232c151bba09ca27e195d39dbcc24
[root@ubuntu1804 ~]#docker port nginx01
80/tcp ->
0.0.0.0:80
[root@ubuntu1804 ~]#lsof -i:80
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
docker-pr 2364 root 4u IPv6 35929 0t0 TCP *:http (LISTEN)
[root@ubuntu1804 ~]#ls
/var/lib/docker/containers/dc5d7c1029e582a3e05890fd18565367482232c151bba09ca27e1
95d39dbcc24/
checkpoints
hostconfig.json mounts
config.v2.json
hostname resolv.conf
dc5d7c1029e582a3e05890fd18565367482232c151bba09ca27e195d39dbcc24-json.log hosts
resolv.conf.hash
[root@ubuntu1804 ~]#systemctl stop docker
[root@ubuntu1804 ~]#vim
/var/lib/docker/containers/dc5d7c1029e582a3e05890fd18565367482232c151bba09ca27e1
95d39dbcc24/hostconfig.json
"PortBindings":"80/tcp":["HostIp":"","HostPort":"80"]
#PortBindings后80/tcp对应的是容器内部的80端口,HostPort对应的是映射到宿主机的端口80 修改此
处为8000
"PortBindings":"80/tcp":["HostIp":"","HostPort":"8000"]
[root@ubuntu1804 ~]#systemctl start docker
[root@ubuntu1804 ~]#docker start nginx01
[root@ubuntu1804 ~]#docker port nginx01
80/tcp ->
0.0.0.0:8000
13、查看容器的日志
- docker logs 可以查看容器中运行的进程在控制台输出的日志信息
- 格式
docker logs [OPTIONS] CONTAINER
选项:
--details Show extra details provided to logs
-f, --follow Follow log output
--since string Show logs since timestamp (e.g. 2013-01-02T13:23:37) or
relative (e.g. 42m for 42 minutes)
--tail string Number of lines to show from the end of the logs (default
"all")
-t, --timestamps Show timestamps
--until string Show logs before a timestamp (e.g. 2013-01-02T13:23:37) or
relative (e.g. 42m for 42 minutes)
- 示例
[root@fsl tmp]# docker logs a1fd8088073d
[root@fsl tmp]# docker logs --tail 3 a1fd8088073d
[root@fsl tmp]# docker logs --tail -f a1fd8088073d#持续刷新
14、 传递运行命令
- 容器需要有一个前台运行的进程才能保持容器的运行,通过传递运行参数是一种方式,另外也可以在构
建镜像的时候指定容器启动时运行的前台命令 - 容器里的PID为1的守护进程的实现方式
- 服务类: 如: Nginx,Tomcat,Apache ,但服务不能停
- 命令类: 如: tail -f /etc/hosts ,主要用于测试环境,注意: 不要tail -f <
服务访问日志>
会产生不
必要的磁盘IO
- 容器会自动将容器的ID加入自已的/etc/hosts文件中,并解析成容器的IP
[root@fsl tmp]# docker exec -it a1fd8088073d bash
[root@a1fd8088073d /]# cat /etc/hosts
127.0.0.1localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.2a1fd8088073d
16、指定容器DNS
- 容器的dns服务器,默认采用宿主机的dns 地址,可以用下面方式指定其它的DNS地址
- 将dns地址配置在宿主机
- 在容器启动时加选项 --dns=x.x.x.x
- 在/etc/docker/daemon.json 文件中指定
[root@ubuntu1804 ~]#systemd-resolve --status|grep -A1 -i "DNS Servers"
DNS Servers: 180.76.76.76
223.6.6.6
[root@ubuntu1804 ~]#docker run -it --rm centos bash
[root@1364f98c4227 /]# cat /etc/resolv.conf
nameserver 180.76.76.76
nameserver 223.6.6.6
search magedu.com magedu.org
[root@1364f98c4227 /]# exit
exit
[root@ubuntu1804 ~]##指定DNS
[root@fsl ~]#docker run -it --rm --dns 1.1.1.1 --dns 8.8.8.8 centos bash#指定domain名
[root@fsl ~]#docker run -it --rm --dns 1.1.1.1 --dns 8.8.8.8 --dns-search
a.com --dns-search b.com busybox#配置文件指定DNS和搜索domain名
[root@fsl ~]#vim /etc/docker/daemon.json
[root@fsl ~]#cat /etc/docker/daemon.json"storage-driver": "overlay2",
"registry-mirrors": ["https://si7y70hh.mirror.aliy
"dns" : [ "114.114.114.114", "119.29.29.29"]
"dns-search": [ "magedu.com", "magedu.org"]#用--dns指定优先级更高
17、 容器内和宿主机之间复制文件
- docker cp
docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH
Options:
-a, --archive Archive mode (copy all uid/gid information)
-L, --follow-link Always follow symbol link in SRC_PATH
- 示例
#将容器内文件复制到宿主机
[root@ubuntu1804 ~]#docker cp -a 1311:/etc/centos-release .
[root@ubuntu1804 ~]#cat centos-release
CentOS Linux release 8.1.1911 (Core)
#将宿主机文件复制到容器内
[root@ubuntu1804 ~]#docker cp /etc/issue 1311:/root/
[root@ubuntu1804 ~]#docker exec 1311 cat /root/issue
19、传递环境变量
- 有些容器运行时,需要传递变量,可以使用 -e < 参数> 或 --env-file < 参数文件> 实现
- 范例: 传递变量创建mysql
- 变量参考链接: https://hub.docker.com/_/mysq
#MySQL容器运行时需要指定root的口令
[root@ubuntu1804 ~]#docker run --name mysql01 mysql:5.7.32
2020-11-16 01:43:13+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL
Server 5.7.32-1debian10 started.
2020-11-16 01:43:13+00:00 [Note] [Entrypoint]: Switching to dedicated user
mysql
2020-11-16 01:43:13+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL
Server 5.7.32-1debian10 started.
2020-11-16 01:43:13+00:00 [ERROR] [Entrypoint]: Database is uninitialized and
password option is not specified
You need to specify one of MYSQL_ROOT_PASSWORD, MYSQL_ALLOW_EMPTY_PASSWORD
and MYSQL_RANDOM_ROOT_PASSWORD
[root@ubuntu1804 ~]#docker run --name mysql-test1 -v /data/mysql:/var/lib/mysql
-e MYSQL_ROOT_PASSWORD=123456 -e MYSQL_DATABASE=wordpress -e MYSQL_USER=wpuser -
e MYSQL_PASSWORD=123456 -d -p 3306:3306 mysql:5.7.30
[root@ubuntu1804 ~]#docker run --name mysql-test2 -v
/root/mysql/:/etc/mysql/conf.d -v /data/mysql2:/var/lib/mysql --envfile=env.list -d -p 3307:3306 mysql:5.7.30
[root@ubuntu1804 ~]#cat mysql/mysql-test.cnf
[mysqld]
server-id=100
log-bin=mysql-bin
[root@ubuntu1804 ~]#cat env.list
MYSQL_ROOT_PASSWORD=123456
MYSQL_DATABASE=wordpress
MYSQL_USER=wpuser
MYSQL_PASSWORD=wppass
命令总结
docker search centos
docker pull alpine
docker images
docker save >
/opt/centos.tar #centos #导出镜像
docker load -i centos-latest.tar.xz #导入本地镜像
docker rmi 镜像ID/镜像名称 #删除指定ID的镜像,此镜像对应容器正启动镜像不能被删除,除非将容器
全部关闭
【docker容器基本操作】容器相关命令
[root@fsl tmp]# docker containerUsage:docker container COMMANDManage containersCommands:
attachAttach local standard input, output, and error streams to a running container
commitCreate a new image from a containers changes
cpCopy files/folders between a container and the local filesystem
createCreate a new container
diffInspect changes to files or directories on a containers filesystem
execRun a command in a running container
exportExport a containers filesystem as a tar archive
inspectDisplay detailed information on one or more containers
killKill one or more running containers
logsFetch the logs of a container
lsList containers
pausePause all processes within one or more containers
portList port mappings or a specific mapping for the container
pruneRemove all stopped containers
renameRename a container
restartRestart one or more containers
rmRemove one or more containers
runRun a command in a new container
startStart one or more stopped containers
statsDisplay a live stream of container(s) resource usage statistics
stopStop one or more running containers
topDisplay the running processes of a container
unpauseUnpause all processes within one or more containers
updateUpdate configuration of one or more containers
waitBlock until one or more containers stop, then print their exit codesRun docker container COMMAND --help for more information on a command.
推荐阅读
- go语言学习--切片
- 一种基于伪标签半监督学习的小样本调制识别算法
- 教你python tkinter实现简单计算器功能
- HTML和ASP之间有哪些区别()
- fork()和exec()之间有什么区别()
- C/C++中float和double有什么区别()
- C语言中的%d和%i格式说明符之间的区别
- C结构和C++结构之间有什么区别()
- const char *p,char *const p和const char * const p之间的区别