46-Docker-Container容器管理各种操作

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了46-Docker-Container容器管理各种操作相关的知识,希望对你有一定的参考价值。

容器相关命令

[root@ubuntu2204 ~]#docker container

Usage: docker container COMMAND

Manage containers

Commands:
attach Attach local standard input, output, and error streams to a running container
commit Create a new image from a containers changes
cp Copy files/folders between a container and the local filesystem
create Create a new container
diff Inspect changes to files or directories on a containers filesystem
exec Run a command in a running container
export Export a containers filesystem as a tar archive
inspect Display detailed information on one or more containers
kill Kill one or more running containers
logs Fetch the logs of a container
ls List containers
pause Pause all processes within one or more containers
port List port mappings or a specific mapping for the container
prune Remove all stopped containers
rename Rename a container
restart Restart one or more containers
rm Remove one or more containers
run Run a command in a new container
start Start one or more stopped containers
stats Display a live stream of container(s) resource usage statistics
stop Stop one or more running containers
top Display the running processes of a container
unpause Unpause all processes within one or more containers
update Update configuration of one or more containers
wait Block until one or more containers stop, then print their exit codes

Run docker container COMMAND --help for more information on a command.

启动并创建容器

docker run = docker create + docker start

  • 复制镜像,生成容器,启动容器,进入容器,并随机生成容器ID和名称

案例:

[root@ubuntu2204 ~]#docker run hello-world

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
1. The Docker client contacted the Docker daemon.
2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
(amd64)
3. The Docker daemon created a new container from that image which runs the
executable that produces the output you are currently reading.
4. The Docker daemon streamed that output to the Docker client, which sent it
to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
$ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
https://hub.docker.com/

For more examples and ideas, visit:
https://docs.docker.com/get-started/

[root@ubuntu2204 ~]#docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx latest 1403e55ab369 2 weeks ago 142MB
alpine latest 49176f190c7e 6 weeks ago 7.05MB
hello-world latest feb5d9fea6a5 15 months ago 13.3kB
[root@ubuntu2204 ~]#docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
0cb0b10c2af5 hello-world "/hello" 2 minutes ago Exited (0) 2 minutes ago angry_wing

案例:一次性运行容器中命令

[root@ubuntu2204 ~]#docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx latest 1403e55ab369 2 weeks ago 142MB
alpine latest 49176f190c7e 6 weeks ago 7.05MB
hello-world latest feb5d9fea6a5 15 months ago 13.3kB
[root@ubuntu2204 ~]#docker run alpine:latest echo "Hello moore"
Hello moore
[root@ubuntu2204 ~]#docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
[root@ubuntu2204 ~]#docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
2a03b18ac322 alpine:latest "echo Hello moore" 18 seconds ago Exited (0) 17 seconds ago condescending_cray
0cb0b10c2af5 hello-world "/hello" 12 minutes ago Exited (0) 12 minutes ago angry_wing

案例:运行交互式容器并退出

[root@ubuntu2204 ~]#docker run -it alpine:latest sh
/ # echo 5+10
5+10
/ # exit
[root@ubuntu2204 ~]#docker ps -l
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
ab636bf080db alpine:latest "sh" 50 seconds ago Exited (0) 16 seconds ago brave_lampor

案例:创建容器后直接进入并退出

[root@ubuntu2204 ~]#docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx latest 1403e55ab369 2 weeks ago 142MB
alpine latest 49176f190c7e 6 weeks ago 7.05MB
hello-world latest feb5d9fea6a5 15 months ago 13.3kB

[root@ubuntu2204 ~]#docker run -it --name alpine01 49176f190c7e
/ # cat /etc/issue
Welcome to Alpine Linux 3.17
Kernel \\r on an \\m (\\l)

/ # hostname
5ff509ad4bee
/ # exit

#退出容器,容器也停止运行
[root@ubuntu2204 ~]#docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
5ff509ad4bee 49176f190c7e "/bin/sh" 2 minutes ago Exited (0) About a minute ago alpine01
b3b92cb5c280 49176f190c7e "--name alpine01" 2 minutes ago Created loving_driscoll

案例:启动后台守护式容器

[root@ubuntu2204 ~]#docker run -d  --name wbe01 nginx:latest
693a57848829cd69fa2f4e7badc6dfa3bffe314f1e840e13c61b23e361cd6310
[root@ubuntu2204 ~]#docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
693a57848829 nginx:latest "/docker-entrypoint.…" 6 seconds ago Up 5 seconds 80/tcp wbe01
[root@ubuntu2204 ~]#docker inspect 693a57848829
...
"Networks":
"bridge":
"IPAMConfig": null,
"Links": null,
"Aliases": null,
"NetworkID": "a8a51592423bd31babd55d1e0538a833d55f279d025178fad9a96352e8752bb5",
"EndpointID": "00819f54d38a220042272cd94e1ffb48efb8a6c7bae085d397219a700aa8be7d",
"Gateway": "172.17.0.1",
"IPAddress": "172.17.0.2", --> 容器ip
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "02:42:ac:11:00:02",
"DriverOpts": null



[root@ubuntu2204 ~]#docker run --rm --name b1 busybox wget -qO - 172.17.0.2
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html color-scheme: light dark;
body width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif;
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

案例:开机自动运行容器

[root@ubuntu2204 ~]#docker run -d --name web02 --restart=always -p 80:80 nginx
672a7868f06f91559d4564148e7cae5f910cf80af57b330da566ad105c106f42
[root@ubuntu2204 ~]#docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
672a7868f06f nginx "/docker-entrypoint.…" 7 seconds ago Up 6 seconds 0.0.0.0:80->80/tcp, :::80->80/tcp web02
693a57848829 nginx:latest "/docker-entrypoint.…" 8 minutes ago Up 8 minutes 80/tcp wbe01
[root@ubuntu2204 ~]#reboot
[root@ubuntu2204 ~]#Connection closing...Socket close.
...

[root@ubuntu2204 ~]#docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
672a7868f06f nginx "/docker-entrypoint.…" 3 minutes ago Up 49 seconds 0.0.0.0:80->80/tcp, :::80->80/tcp web02

案例:启动容器并使其持续运行

[root@ubuntu2204 ~]#docker pull ubuntu
Using default tag: latest
latest: Pulling from library/ubuntu
6e3729cf69e0: Pull complete
Digest: sha256:27cb6e6ccef575a4698b66f5de06c7ecd61589132d5a91d098f7f3f9285415a9
Status: Downloaded newer image for ubuntu:latest
docker.io/library/ubuntu:latest
[root@ubuntu2204 ~]#docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
busybox latest 827365c7baf1 13 days ago 4.86MB
nginx latest 1403e55ab369 2 weeks ago 142MB
ubuntu latest 6b7dfa7e8fdb 3 weeks ago 77.8MB
alpine latest 49176f190c7e 6 weeks ago 7.05MB
hello-world latest feb5d9fea6a5 15 months ago 13.3kB
[root@ubuntu2204 ~]#docker run -it --name ubuntu01 ubuntu
root@9e8ec41bd92c:/# pwd
/
root@9e8ec41bd92c:/# ls
bin boot dev etc home lib lib32 lib64 libx32 media mnt opt proc root run sbin srv sys tmp usr var
#容器内部的文件存放实质上在宿主机
root@9e8ec41bd92c:/# touch mooreyxia.txt
root@9e8ec41bd92c:/# while true; do date +%T >> mooreyxia.txt ;sleep 1;done

#宿主机查看容器内生成的文件
[root@ubuntu2204 ~]#docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
9e8ec41bd92c ubuntu "bash" 52 seconds ago Up 50 seconds ubuntu01
672a7868f06f nginx "/docker-entrypoint.…" 13 minutes ago Up 10 minutes 0.0.0.0:80->80/tcp, :::80->80/tcp web02
[root@ubuntu2204 ~]#docker inspect ubuntu01|grep UpperDir
"UpperDir": "/data/docker/overlay2/bf3e849d2a130fc959cfb4dff4ece3271b994aa853d42772cc158e9d32758a6e/diff",
[root@ubuntu2204 ~]#ls /data/docker/overlay2/bf3e849d2a130fc959cfb4dff4ece3271b994aa853d42772cc158e9d32758a6e/diff
mooreyxia.txt
[root@ubuntu2204 ~]#tail /data/docker/overlay2/bf3e849d2a130fc959cfb4dff4ece3271b994aa853d42772cc158e9d32758a6e/diff/mooreyxia.txt
07:47:57
07:47:58
07:47:59
07:48:00
07:48:01
07:48:03
07:48:04
07:48:05
07:48:06
07:48:07

注意:容器启动后,如果容器内没有前台运行的进程,将自动退出停止


查看容器信息

案例:显示当前存在容器

[root@ubuntu2204 ~]#docker ps --help

Usage: docker ps [OPTIONS]

List containers

Options:
-a, --all Show all containers (default shows just running)
-f, --filter filter Filter output based on conditions provided
--format string Pretty-print containers using a Go template
-n, --last int Show n last created containers (includes all states) (default -1)
-l, --latest Show the latest created container (includes all states)
--no-trunc Dont truncate output
-q, --quiet Only display container IDs
-s, --size Display total file sizes

#显示全部容器
[root@ubuntu2204 ~]#docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
9e8ec41bd92c ubuntu "bash" 18 minutes ago Up 9 minutes ubuntu01
672a7868f06f nginx "/docker-entrypoint.…" 31 minutes ago Up 28 minutes 0.0.0.0:80->80/tcp, :::80->80/tcp web02
693a57848829 nginx:latest "/docker-entrypoint.…" 39 minutes ago Exited (255) 28 minutes ago 80/tcp wbe01

#查看退出状态的容器
[root@ubuntu2204 ~]#docker ps -f status=exited
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
693a57848829 nginx:latest "/docker-entrypoint.…" 42 minutes ago Exited (255) 30 minutes ago 80/tcp wbe01

案例:查看容器内的进程

[root@ubuntu2204 ~]#docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
9e8ec41bd92c ubuntu "bash" 16 minutes ago Up 6 minutes ubuntu01
672a7868f06f nginx "/docker-entrypoint.…" 28 minutes ago Up 25 minutes 0.0.0.0:80->80/tcp, :::80->80/tcp web02
[root@ubuntu2204 ~]#docker top web02
UID PID PPID C STIME TTY TIME CMD
root 1140 1117 0 15:34 ? 00:00:00 nginx: master process nginx -g daemon off;
systemd+ 1201 1140 0 15:34 ? 00:00:00 nginx: worker process
systemd+ 1202 1140 0 15:34 ? 00:00:00 nginx: worker process

案例:查看容器资源使用情况

[root@ubuntu2204 ~]#docker stats web02 > web02_status.txt
^C
[root@ubuntu2204 ~]#cat web02_status.txt

CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
672a7868f06f web02 0.01% 7.117MiB / 1.896GiB 0.37% 1.6kB / 0B 21MB / 8.19kB 3

CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
672a7868f06f web02 0.01% 7.117MiB / 1.896GiB 0.37% 1.6kB / 0B 21MB / 8.19kB 3

CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
672a7868f06f web02 0.00% 7.117MiB / 1.896GiB 0.37% 1.6kB / 0B 21MB / 8.19kB 3

CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
672a7868f06f web02 0.00% 7.117MiB / 1.896GiB 0.37% 1.6kB / 0B 21MB / 8.19kB 3

CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
672a7868f06f web02 0.00% 7.117MiB / 1.896GiB 0.37% 1.6kB / 0B 21MB / 8.19kB 3

CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
672a7868f06f web02 0.00% 7.117MiB / 1.896GiB 0.37% 1.6kB / 0B 21MB / 8.19kB 3

CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
672a7868f06f web02 0.00% 7.117MiB / 1.896GiB 0.37% 1.6kB / 0B 21MB / 8.19kB 3

CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
672a7868f06f web02 0.00% 7.117MiB / 1.896GiB 0.37% 1.6kB / 0B 21MB / 8.19kB 3

CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
672a7868f06f web02 0.00% 7.117MiB / 1.896GiB 0.37% 1.6kB / 0B 21MB / 8.19kB 3

CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
672a7868f06f web02 0.00% 7.117MiB / 1.896GiB 0.37% 1.6kB / 0B 21MB / 8.19kB 3

CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
672a7868f06f web02 0.00% 7.117MiB / 1.896GiB 0.37% 1.6kB / 0B 21MB / 8.19kB 3

CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
672a7868f06f web02 0.00% 7.117MiB / 1.896GiB 0.37% 1.6kB / 0B 21MB / 8.19kB 3

案例:查看容器的详细信息

[root@ubuntu2204 ~]#docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
9e8ec41bd92c ubuntu "bash" 26 minutes ago Up 17 minutes ubuntu01
672a7868f06f nginx "/docker-entrypoint.…" 39 minutes ago Up 36 minutes 0.0.0.0:80->80/tcp, :::80->80/tcp web02
693a57848829 nginx:latest "/docker-entrypoint.…" 48 minutes ago Exited (255) 36 minutes ago 80/tcp wbe01
[root@ubuntu2204 ~]#docker inspect 672
[

"Id": "672a7868f06f91559d4564148e7cae5f910cf80af57b330da566ad105c106f42",
"Created": "2023-01-05T07:32:10.723015257Z",
"Path": "/docker-entrypoint.sh",
"Args": [
"nginx",
"-g",
"daemon off;"
],
"State":
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 1140,
"ExitCode": 0,
"Error": "",
"StartedAt": "2023-01-05T07:34:44.297847995Z",
"FinishedAt": "2023-01-05T15:34:42.627871814+08:00"
,
"Image": "sha256:1403e55ab369cd1c8039c34e6b4d47ca40bbde39c371254c7cba14756f472f52",
"ResolvConfPath": "/data/docker/containers/672a7868f06f91559d4564148e7cae5f910cf80af57b330da566ad105c106f42/resolv.conf",
"HostnamePath": "/data/docker/containers/672a7868f06f91559d4564148e7cae5f910cf80af57b330da566ad105c106f42/hostname",
"HostsPath": "/data/docker/containers/672a7868f06f91559d4564148e7cae5f910cf80af57b330da566ad105c106f42/hosts",
"LogPath": "/data/docker/containers/672a7868f06f91559d4564148e7cae5f910cf80af57b330da566ad105c106f42/672a7868f06f91559d4564148e7cae5f910cf80af57b330da566ad105c106f42-json.log",
"Name": "/web02",
"RestartCount": 0,
"Driver": "overlay2",
"Platform": "linux",
"MountLabel": "",
"ProcessLabel": "",
"AppArmorProfile": "docker-default",
"ExecIDs": null,
"HostConfig":
"Binds": null,
"ContainerIDFile": "",
"LogConfig":
"Type": "json-file",
"Config":
"max-file": "2",
"max-size": "300m"

,
"NetworkMode": "default",
"PortBindings":
"80/tcp": [

"HostIp": "",
"HostPort": "80"

]
,
"RestartPolicy":
"Name": "always",
"MaximumRetryCount": 0
,
"AutoRemove": false,
"VolumeDriver": "",
"VolumesFrom": null,
"CapAdd": null,
"CapDrop": null,
"CgroupnsMode": "private",
"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": null,
"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": "/data/docker/overlay2/e4aa5141a37f74d4a25a6fc62b976a9cb3b4cae226b563e6d2763672be57a9e2-init/diff:/data/docker/overlay2/25ebf3757e65a5d01803e27214304288689844af5d247da930eda9314f73e4af/diff:/data/docker/overlay2/d1bfc2060ff074bfc29d071897f5f0fbd53d08eb65aa4ebc0254c605d1d8e7e1/diff:/data/docker/overlay2/aded9ef9c146c1aa21183dd21f8949125b489dc31b1b943ec278b4f5986e5319/diff:/data/docker/overlay2/e894eaf5b71767c6956f09c20768ea81a65e9c1477d5a08821d634fe58a888c8/diff:/data/docker/overlay2/f7ad75e3645a7d6b9c77c35a547c6bf421170d206d006674873427eab92c392e/diff:/data/docker/overlay2/0812214ceaaa259893a78e3df52e3e787594d92d676ef3c1c3ce9a4f9453b705/diff",
"MergedDir": "/data/docker/overlay2/e4aa5141a37f74d4a25a6fc62b976a9cb3b4cae226b563e6d2763672be57a9e2/merged",
"UpperDir": "/data/docker/overlay2/e4aa5141a37f74d4a25a6fc62b976a9cb3b4cae226b563e6d2763672be57a9e2/diff",
"WorkDir": "/data/docker/overlay2/e4aa5141a37f74d4a25a6fc62b976a9cb3b4cae226b563e6d2763672be57a9e2/work"
,
"Name": "overlay2"
,
"Mounts": [],
"Config":
"Hostname": "672a7868f06f",
"Domainname": "",
"User": "",
"AttachStdin": false,
"AttachStdout": false,
"AttachStderr": false,
"ExposedPorts":
"80/tcp":
,
"Tty": false,
"OpenStdin": false,
"StdinOnce": false,
"Env": [
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"NGINX_VERSION=1.23.3",
"NJS_VERSION=0.7.9",
"PKG_RELEASE=1~bullseye"
],
"Cmd": [
"nginx",
"-g",
"daemon off;"
],
"Image": "nginx",
"Volumes": null,
"WorkingDir": "",
"Entrypoint": [
"/docker-entrypoint.sh"
],
"OnBuild": null,
"Labels":
"maintainer": "NGINX Docker Maintainers <docker-maint@nginx.com>"
,
"StopSignal": "SIGQUIT"
,
"NetworkSettings":
"Bridge": "",
"SandboxID": "fa69dc2f2e74ad7dc54a270aa808403835ab02be2f7b58cd97154a3d0127c179",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports":
"80/tcp": [

"HostIp": "0.0.0.0",
"HostPort": "80"
,

"HostIp": "::",
"HostPort": "80"

]
,
"SandboxKey": "/var/run/docker/netns/fa69dc2f2e74",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "21e23a3a7028a7f588563e4b13eb98424b0f475f5608ea1df1781c83acdca658",
"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": "0e25eb364b81a8636738882ca0bab228d3d98d44fd59c49914752543594dfedf",
"EndpointID": "21e23a3a7028a7f588563e4b13eb98424b0f475f5608ea1df1781c83acdca658",
"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




]

删除容器

案例:删除指定状态的容器

[root@ubuntu2204 ~]#docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
9e8ec41bd92c ubuntu "bash" 30 minutes ago Up 20 minutes ubuntu01
672a7868f06f nginx "/docker-entrypoint.…" 42 minutes ago Up 40 minutes 0.0.0.0:80->80/tcp, :::80->80/tcp web02
693a57848829 nginx:latest "/docker-entrypoint.…" 51 minutes ago Exited (255) 40 minutes ago 80/tcp wbe01
[root@ubuntu2204 ~]#docker rm `docker ps -qf status=exited`
693a57848829
[root@ubuntu2204 ~]#docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
9e8ec41bd92c ubuntu "bash" 31 minutes ago Up 21 minutes ubuntu01
672a7868f06f nginx "/docker-entrypoint.…" 43 minutes ago Up 40 minutes 0.0.0.0:80->80/tcp, :::80->80/tcp web02

案例:清理全部容器 - 慎用

[root@ubuntu2204 ~]#docker rm -f `docker ps -qa`
653687662f0f
045dd528e93b
5ff509ad4bee
b3b92cb5c280
0da8a6de10ca
ab636bf080db
2a03b18ac322
0cb0b10c2af5
[root@ubuntu2204 ~]#docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES

进入正在运行的容器

案例:

[root@ubuntu2204 ~]#docker exec -it web02 bash
root@672a7868f06f:/# pwd
/
root@672a7868f06f:/# ls
bin boot dev docker-entrypoint.d docker-entrypoint.sh etc home lib lib64 media mnt opt proc root run sbin srv sys tmp usr var
root@672a7868f06f:/# cat /etc/nginx/nginx.conf

user nginx;
worker_processes auto;

error_log /var/log/nginx/error.log notice;
pid /var/run/nginx.pid;


events
worker_connections 1024;



http
include /etc/nginx/mime.types;
default_type application/octet-stream;

log_format main $remote_addr - $remote_user [$time_local] "$request"
$status $body_bytes_sent "$http_referer"
"$http_user_agent" "$http_x_forwarded_for";

access_log /var/log/nginx/access.log main;

sendfile on;
#tcp_nopush on;

keepalive_timeout 65;

#gzip on;

include /etc/nginx/conf.d/*.conf;

#exec的方式 exit退出容器也不会停止
root@672a7868f06f:/# exit
exit
[root@ubuntu2204 ~]#docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
9e8ec41bd92c ubuntu "bash" 39 minutes ago Up 30 minutes ubuntu01
672a7868f06f nginx "/docker-entrypoint.…" 52 minutes ago Up 49 minutes 0.0.0.0:80->80/tcp, :::80->80/tcp web02

Docker端口暴露实现跨宿主机访问

容器启动后,默认处于预定义的NAT网络中,所以外部网络的主机无法直接访问容器中网络服务docker run -P 可以将事先容器预定义的所有端口映射宿主机的网卡的随机端口,默认从32768开始使用随机端口 时,当停止容器后再启动可能会导致端口发生变化

案例:容器跨宿主机访问

#创建nginx容器并运行
[root@ubuntu2204 ~]#docker run -d -p 8080:80 --name web01 nginx
99b824abe4cb4779a16058401600b3e1676a18d74070742b3220019f7b14ffaf
[root@ubuntu2204 ~]#docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
99b824abe4cb nginx "/docker-entrypoint.…" 8 seconds ago Up 7 seconds 0.0.0.0:8080->80/tcp, :::8080->80/tcp web01
9e8ec41bd92c ubuntu "bash" About an hour ago Up 55 minutes ubuntu01
672a7868f06f nginx "/docker-entrypoint.…" About an hour ago Up About an hour 0.0.0.0:80->80/tcp, :::80->80/tcp web02

#观察宿主机,发现生成新的网卡
[root@ubuntu2204 ~]#ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
link/ether 00:0c:29:df:99:92 brd ff:ff:ff:ff:ff:ff
altname enp2s1
altname ens33
inet 10.0.0.200/24 brd 10.0.0.255 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::20c:29ff:fedf:9992/64 scope link
valid_lft forever preferred_lft forever
3: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 02:42:06:86:b5:d5 brd ff:ff:ff:ff:ff:ff
inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
valid_lft forever preferred_lft forever
inet6 fe80::42:6ff:fe86:b5d5/64 scope link
valid_lft forever preferred_lft forever
5: veth4fb03da@if4: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker0 state UP group default
link/ether d6:c3:aa:57:7b:50 brd ff:ff:ff:ff:ff:ff link-netnsid 0
inet6 fe80::d4c3:aaff:fe57:7b50/64 scope link
valid_lft forever preferred_lft forever
9: veth64ce510@if8: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker0 state UP group default
link/ether 0a:7a:11:2b:d1:ee brd ff:ff:ff:ff:ff:ff link-netnsid 1
inet6 fe80::87a:11ff:fe2b:d1ee/64 scope link
valid_lft forever preferred_lft forever
11: veth1f9e256@if10: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker0 state UP group default --> 新出现的网卡
link/ether d6:27:ba:37:a3:0a brd ff:ff:ff:ff:ff:ff link-netnsid 2
inet6 fe80::d427:baff:fe37:a30a/64 scope link
valid_lft forever preferred_lft forever

#实验中途观察结果就是只要多一个正在运行的容器就多一张网卡,配合容器的IP成对使用,配置如下

46-Docker-Container容器管理各种操作_容器管理

w说明默认容器网络只支持宿主机内部网络通讯【宿主机或其他容器】,而不支持跨宿主机。

#宿主机内部容器互相访问
#web02
[root@ubuntu2204 ~]#docker exec -it web02 bash
root@672a7868f06f:/# hostname -I
172.17.0.2
root@672a7868f06f:/# cat /usr/share/nginx/html/index.html
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html color-scheme: light dark;
body width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif;
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
root@672a7868f06f:/# echo docker-nginx-web02 > /usr/share/nginx/html/index.html
root@672a7868f06f:/# exit
exit

#web01
[root@ubuntu2204 ~]#docker exec -it web01 bash
root@99b824abe4cb:/# hostname -I
172.17.0.4
root@99b824abe4cb:/# apt update;apt install curl
Get:1 http://deb.debian.org/debian bullseye InRelease [116 kB]
Get:2 http://deb.debian.org/debian-security bullseye-security InRelease [48.4 kB]
Get:3 http://deb.debian.org/debian bullseye-updates InRelease [44.1 kB]
Get:4 http://deb.debian.org/debian bullseye/main amd64 Packages [8183 kB]
Get:5 http://deb.debian.org/debian-security bullseye-security/main amd64 Packages [210 kB]
Get:6 http://deb.debian.org/debian bullseye-updates/main amd64 Packages [14.6 kB]
Fetched 8616 kB in 2min 57s (48.6 kB/s)
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
All packages are up to date.
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
curl is already the newest version (7.74.0-1.3+deb11u3).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
root@99b824abe4cb:/# curl 172.17.0.2
docker-nginx-web02

#也可以访问外部网络
root@99b824abe4cb:/# curl www.xxx.com
<!DOCTYPE html>
xxx

由于是宿主机内部网络通信,可以看作一个局域网,使外网能访问内网docker就需要做DNAT端口映射

  • DNAT docker_IP:端口 ---> 宿主机_IP:端口

*注意: 多个容器映射到宿主机的端口不能冲突,但容器内使用的端口可以相同

#默认的容器网络规则
[root@ubuntu2204 ~]#iptables -S
...
-A DOCKER -d 172.17.0.2/32 ! -i docker0 -o docker0 -p tcp -m tcp --dport 80 -j ACCEPT
-A DOCKER -d 172.17.0.4/32 ! -i docker0 -o docker0 -p tcp -m tcp --dport 80 -j ACCEPT
...
#使用docker自带的映射选项可以省去iptables的操作,添加DNAT端口映射,使用P会绑定到宿主机的随机端口,这里我们p指定端口
*注意: 多个容器映射到宿主机的端口不能冲突,但容器内使用的端口可以相同
#web01 映射到宿主机8080端口
[root@ubuntu2204 ~]#docker run -d -p 8080:80 --name web01 nginx
#web02 映射到宿主机80端口
[root@ubuntu2204 ~]#docker run -d -p 80:80 --name web02 nginx
#端口转换规则
[root@ubuntu2204 ~]#docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
99b824abe4cb nginx "/docker-entrypoint.…" 41 minutes ago Up 41 minutes 0.0.0.0:8080->80/tcp, :::8080->80/tcp web01
9e8ec41bd92c ubuntu "bash" 2 hours ago Up 2 hours ubuntu01
672a7868f06f nginx "/docker-entrypoint.…" 2 hours ago Up 2 hours 0.0.0.0:80->80/tcp, :::80->80/tcp web02
[root@ubuntu2204 ~]#docker port web01
80/tcp -> 0.0.0.0:8080
80/tcp -> :::8080
[root@ubuntu2204 ~]#docker port web02
80/tcp -> 0.0.0.0:80
80/tcp -> :::80
[root@ubuntu2204 ~]#iptables -vnL -t nat
Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
4 224 DOCKER all -- * * 0.0.0.0/0 0.0.0.0/0 ADDRTYPE match dst-type LOCAL

Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
0 0 DOCKER all -- * * 0.0.0.0/0 !127.0.0.0/8 ADDRTYPE match dst-type LOCAL

Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
6 358 MASQUERADE all -- * !docker0 172.17.0.0/16 0.0.0.0/0
0 0 MASQUERADE tcp -- * * 172.17.0.2 172.17.0.2 tcp dpt:80
0 0 MASQUERADE tcp -- * * 172.17.0.4 172.17.0.4 tcp dpt:80

Chain DOCKER (2 references)
pkts bytes target prot opt in out source destination
0 0 RETURN all -- docker0 * 0.0.0.0/0 0.0.0.0/0
1 60 DNAT tcp -- !docker0 * 0.0.0.0/0 0.0.0.0/0 tcp dpt:80 to:172.17.0.2:80
1 60 DNAT tcp -- !docker0 * 0.0.0.0/0 0.0.0.0/0 tcp dpt:8080 to:172.17.0.4:80
[root@ubuntu2204 ~]#ss -nltp
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
...
LISTEN 0 4096 [::]:8080 [::]:* users:(("docker-proxy",pid=2409,fd=4))
LISTEN 0 4096 [::]:80 [::]:* users:(("docker-proxy",pid=1100,fd=4))

#测试跨宿主机访问内部docker服务
[root@ubuntu2204 ~]#curl 10.0.0.200:8080
docker-nginx-web01
[root@ubuntu2204 ~]#curl 10.0.0.200:80
docker-nginx-web02

案例:修改已经创建的容器的端口映射关系

[root@ubuntu2204 ~]#docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
99b824abe4cb nginx "/docker-entrypoint.…" 2 hours ago Up 2 hours 0.0.0.0:8080->80/tcp, :::8080->80/tcp web01
9e8ec41bd92c ubuntu "bash" 3 hours ago Up 3 hours ubuntu01
672a7868f06f nginx "/docker-entrypoint.…" 4 hours ago Up 4 hours 0.0.0.0:80->80/tcp, :::80->80/tcp web02

[root@ubuntu2204 ~]#docker port web01
80/tcp -> 0.0.0.0:8080
80/tcp -> :::8080

[root@ubuntu2204 ~]#ll /data/docker/containers/99b824abe4cb4779a16058401600b3e1676a18d74070742b3220019f7b14ffaf/
总用量 44
drwx--x--- 4 root root 4096 1月 5 16:49 ./
drwx--x--- 5 root root 4096 1月 5 16:49 ../
-rw-r----- 1 root root 2470 1月 5 17:32 99b824abe4cb4779a16058401600b3e1676a18d74070742b3220019f7b14ffaf-json.log
drwx------ 2 root root 4096 1月 5 16:49 checkpoints/
-rw------- 1 root root 2906 1月 5 16:49 config.v2.json
-rw-r--r-- 1 root root 1548 1月 5 16:49 hostconfig.json
-rw-r--r-- 1 root root 13 1月 5 16:49 hostname
-rw-r--r-- 1 root root 174 1月 5 16:49 hosts
drwx--x--- 2 root root 4096 1月 5 16:49 mounts/
-rw-r--r-- 1 root root 824 1月 5 16:49 resolv.conf
-rw-r--r-- 1 root root 71 1月 5 16:49 resolv.conf.hash

[root@ubuntu2204 ~]#systemctl stop docker
Warning: Stopping docker.service, but it can still be activated by:
docker.socket
[root@ubuntu2204 ~]#cd /data/docker/containers/99b824abe4cb4779a16058401600b3e1676a18d74070742b3220019f7b14ffaf/
[root@ubuntu2204 99b824abe4cb4779a16058401600b3e1676a18d74070742b3220019f7b14ffaf]#vim hostconfig.json
#PortBindings后80/tcp对应的是容器内部的80端口,HostPort对应的是映射到宿主机的端口8080 修改此处为8090
[root@ubuntu2204 99b824abe4cb4779a16058401600b3e1676a18d74070742b3220019f7b14ffaf]#cat hostconfig.json
"PortBindings":"80/tcp":["HostIp":"","HostPort":"8090"]

[root@ubuntu2204 ~]#systemctl restart docker.service
[root@ubuntu2204 ~]#docker restart web01
web01
[root@ubuntu2204 ~]#docker port web01
80/tcp -> 0.0.0.0:8090
80/tcp -> :::8090

#测试
[root@ubuntu2204 ~]#curl 10.0.0.200:8090
docker-nginx-web01

查看容器的日志

案例:查看nginx服务访问日志 - 记录的是容器内部信息

[root@ubuntu2204 ~]#docker logs --help

Usage: docker logs [OPTIONS] CONTAINER

Fetch the logs of a container

Options:
--details Show extra details provided to logs
-f, --follow Follow log output
--since string Show logs since timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g. 42m for 42 minutes)
-n, --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:37Z) or relative (e.g. 42m for 42 minutes)
[root@ubuntu2204 ~]#docker logs web01
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
....

#跟踪实时变化
[root@ubuntu2204 ~]#curl 10.0.0.200:8090
docker-nginx-web01
[root@ubuntu2204 ~]#docker logs -f web01
10.0.0.202 - - [05/Jan/2023:11:24:32 +0000] "GET / HTTP/1.1" 200 19 "-" "curl/7.81.0" "-"

#容器的日志实际上利用的是宿主机的标准输出重定向
[root@ubuntu2204 ~]#docker inspect web01|grep MergedDir
"MergedDir": "/data/docker/overlay2/240e12aaba372423a74dff3eb30f9f0fb9570add8620bb8557390c9423b847ff/merged",
[root@ubuntu2204 ~]#ls /data/docker/overlay2/240e12aaba372423a74dff3eb30f9f0fb9570add8620bb8557390c9423b847ff/merged/
[root@ubuntu2204 ~]#ll /data/docker/overlay2/240e12aaba372423a74dff3eb30f9f0fb9570add8620bb8557390c9423b847ff/merged/var/log/nginx/
总用量 8
drwxr-xr-x 2 root root 4096 12月 21 19:28 ./
drwxr-xr-x 1 root root 4096 12月 21 19:28 ../
lrwxrwxrwx 1 root root 11 12月 21 19:28 access.log -> /dev/stdout
lrwxrwxrwx 1 root root 11 12月 21 19:28 error.log -> /dev/stderr

注意:

当log中没有记录docker运行错误,比如设置错误导致docker跑不起来,日志服务跑不起来,就用inspect去查看

  • 搭配使用 logs 和 inspect

容器内部的hosts文件

容器会自动将容器的ID加入自已的/etc/hosts文件中,并解析成容器的IP

[root@ubuntu2204 ~]#docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
99b824abe4cb nginx "/docker-entrypoint.…" 3 hours ago Up 15 minutes 0.0.0.0:8090->80/tcp, :::8090->80/tcp web01

[root@ubuntu2204 ~]#docker exec -it web01 bash
root@99b824abe4cb:/# hostname -I
172.17.0.4
root@99b824abe4cb:/# cat /etc/hosts
127.0.0.1 localhost
::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.4 99b824abe4cb
root@99b824abe4cb:/# hostname
99b824abe4cb --> container ID

案例:在宿主机修改容器的域名

[root@ubuntu2204 ~]#docker run -d --add-host web03:172.17.0.10 --name alpine01 alpine tail -f /etc/hosts
a599c84e3641d1b2a3da716fc7d5aa5192ca39fe506017bb668115683adb28d1
[root@ubuntu2204 ~]#docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
a599c84e3641 alpine "tail -f /etc/hosts" 6 seconds ago Up 5 seconds alpine01
99b824abe4cb nginx "/docker-entrypoint.…" 3 hours ago Up 23 minutes 0.0.0.0:8090->80/tcp, :::8090->80/tcp web01
9e8ec41bd92c ubuntu "bash" 4 hours ago Up 4 hours ubuntu01
672a7868f06f nginx "/docker-entrypoint.…" 4 hours ago Up 4 hours 0.0.0.0:80->80/tcp, :::80->80/tcp web02
[root@ubuntu2204 ~]#docker exec -it alpine01 sh
/ # cat /etc/hosts
127.0.0.1 localhost
::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.10 web03
172.17.0.5 a599c84e3641
/ #

指定容器DNS

容器的dns服务器,默认采用宿主机的dns 地址,可以用下面方式指定其它的DNS地址

  • 将dns地址配置在宿主机
  • 在容器启动时加选项 --dns=x.x.x.x
  • 在/etc/docker/daemon.json 文件中指定

容器的DNS默认从宿主机的DNS获取

#容器默认DNS
[root@ubuntu2204 ~]#docker exec -it web01 bash
root@99b824abe4cb:/# cat /etc/resolv.conf
# This is /run/systemd/resolve/resolv.conf managed by man:systemd-resolved(8).
# Do not edit.
#
# This file might be symlinked as /etc/resolv.conf. If youre looking at
# /etc/resolv.conf and seeing this text, you have followed the symlink.
#
# This is a dynamic resolv.conf file for connecting local clients directly to
# all known uplink DNS servers. This file lists all configured search domains.
#
# Third party programs should typically not access this file directly, but only
# through the symlink at /etc/resolv.conf. To manage man:resolv.conf(5) in a
# different way, replace this symlink by a static file or a different symlink.
#
# See man:systemd-resolved.service(8) for details about the supported modes of
# operation for /etc/resolv.conf.

nameserver 180.76.76.76
nameserver 223.6.6.6
search mooreyxia.org mooreyxia.com

#查看宿主机DNS
[root@ubuntu2204 ~]#cat /etc/resolv.conf
# This is /run/systemd/resolve/stub-resolv.conf managed by man:systemd-resolved(8).
# Do not edit.
#
# This file might be symlinked as /etc/resolv.conf. If youre looking at
# /etc/resolv.conf and seeing this text, you have followed the symlink.
#
# This is a dynamic resolv.conf file for connecting local clients to the
# internal DNS stub resolver of systemd-resolved. This file lists all
# configured search domains.
#
# Run "resolvectl status" to see details about the uplink DNS servers
# currently in use.
#
# Third party programs should typically not access this file directly, but only
# through the symlink at /etc/resolv.conf. To manage man:resolv.conf(5) in a
# different way, replace this symlink by a static file or a different symlink.
#
# See man:systemd-resolved.service(8) for details about the supported modes of
# operation for /etc/resolv.conf.

nameserver 127.0.0.53
options edns0 trust-ad
search mooreyxia.org mooreyxia.com

[root@ubuntu2204 ~]#resolvectl status
Global
Protocols: -LLMNR -mDNS -DNSOverTLS DNSSEC=no/unsupported
resolv.conf mode: stub

Link 2 (eth0)
Current Scopes: DNS
Protocols: +DefaultRoute +LLMNR -mDNS -DNSOverTLS DNSSEC=no/unsupported
Current DNS Server: 180.76.76.76
DNS Servers: 180.76.76.76 223.6.6.6
DNS Domain: mooreyxia.com mooreyxia.org

Link 3 (docker0)
Current Scopes: none
Protocols: -DefaultRoute +LLMNR -mDNS -DNSOverTLS DNSSEC=no/unsupported

案例:指定容器DNS地址

[root@ubuntu2204 /]#docker run -it --rm --name a1  --dns 1.1.1.1 --dns 8.8.8.8 alpine sh
/ # cat /etc/resolv.conf
search mooreyxia.org mooreyxia.com
nameserver 1.1.1.1
nameserver 8.8.8.8

案例:指定domain名

[root@ubuntu2204 /]#docker run -it --rm --dns 1.1.1.1 --dns 8.8.8.8 --dns-search a.com --dns-search b.com busybox sh
/ # cat /etc/resolv.conf
search a.com b.com
nameserver 1.1.1.1
nameserver 8.8.8.8

案例:配置文件指定DNS和搜索domain名

[root@ubuntu2204 /]#vim /etc/docker/daemon.json 
[root@ubuntu2204 /]#cat /etc/docker/daemon.json

"registry-mirrors": [
"https://registry.docker-cn.com",
"http://hub-mirror.c.163.com",
"https://docker.mirrors.ustc.edu.cn"
],
"graph": "/data/docker",
"graph": "/data/docker",
"max-concurrent-downloads": 10,
"max-concurrent-uploads": 5,
"log-opts":
"max-size": "300m",
"max-file": "2"
,
"live-restore": true,
"dns" : [ "114.114.114.114", "119.29.29.29"], --> 在这里指定
"dns-search": [ "mooreyxia.com", "mooreyxia.org"] --> 在这里指定

[root@ubuntu2204 /]#systemctl restart docker
[root@ubuntu2204 /]#docker run -it --rm busybox sh
/ # cat /etc/resolv.conf
search mooreyxia.com mooreyxia.org
nameserver 114.114.114.114
nameserver 119.29.29.29
/ #

容器内和宿主机之间复制文件

案例:

[root@ubuntu2204 /]#docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
99b824abe4cb nginx "/docker-entrypoint.…" 5 hours ago Up 3 hours 0.0.0.0:8090->80/tcp, :::8090->80/tcp web01
9e8ec41bd92c ubuntu "bash" 6 hours ago Up 6 hours ubuntu01
672a7868f06f nginx "/docker-entrypoint.…" 6 hours ago Up 6 hours 0.0.0.0:80->80/tcp, :::80->80/tcp web02


#将容器内文件复制到宿主机
[root@ubuntu2204 /]#docker cp -a 9e8ec41bd92c:/etc/os-release .
[root@ubuntu2204 /]#cat os-release
PRETTY_NAME="Ubuntu 22.04.1 LTS"
NAME="Ubuntu"
VERSION_ID="22.04"
VERSION="22.04.1 LTS (Jammy Jellyfish)"
VERSION_CODENAME=jammy
ID=ubuntu
ID_LIKE=debian
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
UBUNTU_CODENAME=jammy

#将宿主机文件复制到容器内
[root@ubuntu2204 /]#docker cp /root/install_docker.sh 9e8ec41bd92c:/root/
root@9e8ec41bd92c:/# cd /root/
root@9e8ec41bd92c:~# ll
total 28
drwx------ 1 root root 4096 Jan 5 14:03 ./
drwxr-xr-x 1 root root 4096 Jan 5 14:03 ../
-rw------- 1 root root 108 Jan 5 07:57 .bash_history
-rw-r--r-- 1 root root 3106 Oct 15 2021 .bashrc
-rw-r--r-- 1 root root 161 Jul 9 2019 .profile
-rw-r--r-- 1 root root 4445 Dec 29 15:08 install_docker.sh

使用 systemd 控制容器运行

[root@ubuntu2204 ~]#vim /lib/systemd/system/hello.service
[root@ubuntu2204 ~]#cat /lib/systemd/system/hello.service
[Unit]
Description=Hello World
After=docker.service
Requires=docker.service
[Service]
TimeoutStartSec=0
ExecStartPre=-/usr/bin/docker kill busybox-hello
ExecStartPre=-/usr/bin/docker rm busybox-hello
ExecStartPre=/usr/bin/docker pull busybox
ExecStart=/usr/bin/docker run --name busybox-hello busybox /bin/sh -c "while true; do echo Hello World; sleep 1; done"
ExecStop=/usr/bin/docker kill busybox-hello
[Install]
WantedBy=multi-user.target
[root@ubuntu2204 ~]#systemctl daemon-reload
[root@ubuntu2204 ~]#systemctl enable --now hello.service
[root@ubuntu2204 ~]#systemctl status hello.service
● hello.service - Hello World
Loaded: loaded (/lib/systemd/system/hello.service; enabled; vendor preset: enabled)
Active: active (running) since Thu 2023-01-05 22:11:18 CST; 26s ago
Process: 29145 ExecStartPre=/usr/bin/docker kill busybox-hello (code=exited, status=1/FAILURE)
Process: 29152 ExecStartPre=/usr/bin/docker rm busybox-hello (code=exited, status=1/FAILURE)
Process: 29158 ExecStartPre=/usr/bin/docker pull busybox (code=exited, status=0/SUCCESS)
Main PID: 29182 (docker)
Tasks: 7 (limit: 2196)
Memory: 17.5M
CPU: 223ms
CGroup: /system.slice/hello.service
└─29182 /usr/bin/docker run --name busybox-hello busybox /bin/sh -c "while true; do echo Hello World; sleep 1; done"

1月 05 22:11:35 ubuntu2204.wang.org docker[29182]: Hello World
1月 05 22:11:36 ubuntu2204.wang.org docker[29182]: Hello World
1月 05 22:11:37 ubuntu2204.wang.org docker[29182]: Hello World
1月 05 22:11:38 ubuntu2204.wang.org docker[29182]: Hello World
1月 05 22:11:39 ubuntu2204.wang.org docker[29182]: Hello World
1月 05 22:11:40 ubuntu2204.wang.org docker[29182]: Hello World
1月 05 22:11:41 ubuntu2204.wang.org docker[29182]: Hello World
1月 05 22:11:42 ubuntu2204.wang.org docker[29182]: Hello World
1月 05 22:11:43 ubuntu2204.wang.org docker[29182]: Hello World
1月 05 22:11:44 ubuntu2204.wang.org docker[29182]: Hello World

[root@ubuntu2204 ~]#docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
854f520cdf92 busybox "/bin/sh -c while t…" 54 seconds ago Up 53 seconds busybox-hello

[root@ubuntu2204 ~]#systemctl stop hello.service
[root@ubuntu2204 ~]#systemctl status hello.service
× hello.service - Hello World
Loaded: loaded (/lib/systemd/system/hello.service; enabled; vendor preset: enabled)
Active: failed (Result: exit-code) since Thu 2023-01-05 22:13:01 CST; 3s ago
Process: 29145 ExecStartPre=/usr/bin/docker kill busybox-hello (code=exited, status=1/FAILURE)
Process: 29152 ExecStartPre=/usr/bin/docker rm busybox-hello (code=exited, status=1/FAILURE)
Process: 29158 ExecStartPre=/usr/bin/docker pull busybox (code=exited, status=0/SUCCESS)
Process: 29182 ExecStart=/usr/bin/docker run --name busybox-hello busybox /bin/sh -c while true; do echo Hello World; sleep 1; done (code=exited, status=137)
Process: 29386 ExecStop=/usr/bin/docker kill busybox-hello (code=exited, status=0/SUCCESS)
Main PID: 29182 (code=exited, status=137)
CPU: 294ms

1月 05 22:12:56 ubuntu2204.wang.org docker[29182]: Hello World
1月 05 22:12:57 ubuntu2204.wang.org docker[29182]: Hello World
1月 05 22:12:58 ubuntu2204.wang.org docker[29182]: Hello World
1月 05 22:12:59 ubuntu2204.wang.org docker[29182]: Hello World
1月 05 22:13:00 ubuntu2204.wang.org docker[29182]: Hello World
1月 05 22:13:00 ubuntu2204.wang.org systemd[1]: Stopping Hello World...
1月 05 22:13:01 ubuntu2204.wang.org docker[29386]: busybox-hello
1月 05 22:13:01 ubuntu2204.wang.org systemd[1]: hello.service: Main process exited, code=exited, status=137/n/a
1月 05 22:13:01 ubuntu2204.wang.org systemd[1]: hello.service: Failed with result exit-code.
1月 05 22:13:01 ubuntu2204.wang.org systemd[1]: Stopped Hello World.

传递环境变量

案例:

[root@ubuntu2204 ~]#docker run -e P1=moore -e PDATE=2023-01-05 --name b1 busybox env
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=ca41f601d231
P1=moore
PDATE=2023-01-05
HOME=/root

#数据路创建
[root@ubuntu2204 ~]#docker run --restart always -d --name mysql01 mysql:5.7.32
Unable to find image mysql:5.7.32 locally
5.7.32: Pulling from library/mysql
a076a628af6f: Downloading
f6c208f3f991: Download complete
88a9455a9165: Download complete
406c9b8427c6: Download complete
7c88599c0b25: Download complete
25b5c6debdaf: Download complete
43a5816f1617: Download complete
7065aaa2655f: Download complete
b4bc531db40f: Download complete
8c3e9d7c9815: Download complete
fadfb9734ed2: Download complete
5.7.32: Pulling from library/mysql
a076a628af6f: Pull complete
f6c208f3f991: Pull complete
88a9455a9165: Pull complete
406c9b8427c6: Pull complete
7c88599c0b25: Pull complete
25b5c6debdaf: Pull complete
43a5816f1617: Pull complete
7065aaa2655f: Pull complete
b4bc531db40f: Pull complete
8c3e9d7c9815: Pull complete
fadfb9734ed2: Pull complete
Digest: sha256:e08834258fcc0efd01df358222333919df53d4a0d9b2a54da05b204b822e3b7b
Status: Downloaded newer image for mysql:5.7.32
cc666443d2d1c8d3ec355f4e3205e827eed43c6bff009dccb59c1d71f777c8bc

[root@ubuntu2204 ~]#docker run --name mysq

以上是关于46-Docker-Container容器管理各种操作的主要内容,如果未能解决你的问题,请参考以下文章

docker安装和各种操作

容器云运维管理岗——容器云运维架构设计方向辅导答疑

终端的Docker管理ui,不用再记各种命令啦

Portainer堪称最优秀的容器化管理平台

容器的分类与各种测试——deque

Spring 中 IoC 容器简介