容器-Docker《三》容器管理
下载镜像只是相当于将软件下载下来安装好,但是并不代表把它运行起来,类似于root@ubuntu2204:~# apt install nginx = docker pull nginx ,然而进行运行起来就变成了容器,镜像只是模板文件,容器复制一份模板文件生成相关进程对外提供服务,随着运行的时间推移容器除了模板文件还会生成别的文件。
那么一个机器里面可以运行两个容器跑两个nginx吗?
root@ubuntu2204:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
be01627007fb nginx:latest "/docker-entrypoint.…" About a minute ago Up About a minute 80/tcp priceless_nightingale
8dd8f5328dff nginx:latest "/docker-entrypoint.…" 34 minutes ago Up 10 minutes 80/tcp boring_goldstine
root@ubuntu2204:~# ps axu|grep nginx
root 6576 0.0 0.1 8856 5516 ? Ss 12:53 0:00 nginx: master process nginx -g daemon off;
systemd+ 6628 0.0 0.0 9276 2672 ? S 12:53 0:00 nginx: worker process
systemd+ 6629 0.0 0.0 9276 2672 ? S 12:53 0:00 nginx: worker process
root 6655 0.0 1.2 1273784 49348 pts/6 Sl+ 13:02 0:00 docker run nginx:latest
root 6724 0.0 0.1 8856 5508 ? Ss 13:02 0:00 nginx: master process nginx -g daemon off;
systemd+ 6774 0.0 0.0 9276 2588 ? S 13:02 0:00 nginx: worker process
systemd+ 6775 0.0 0.0 9276 2588 ? S 13:02 0:00 nginx: worker process
root 6908 0.0 0.0 6608 2264 pts/8 R+ 13:08 0:00 grep --color=auto nginx
容器是一个在主机上运行的进程 ,主机可以是本地主机,也可以是远程主机。运行的容器进程被隔离,容器有自己的文件系统、自己的网络和自己的 独立于主机的独立进程树。
image:文件模板,仅是文件,只消耗磁盘空间,静态概念;container:复制模板文件生成新的文件和进程,即消耗磁盘空间也消耗内存空间,动态概念,有生命期。
1,容器生命周期
root@ubuntu2204:~# docker container --help
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 container's 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 container's filesystem
exec Run a command in a running container
export Export a container's 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.
root@ubuntu2204:~#
容器启动流程
Docker----Docker容器的启动流程:https://developer.aliyun.com/article/920837
为了后续做实验,将Docker数据根目录更改为/data/docker ,和添加镜像加速器。
root@ubuntu2204:~# docker info
Client:
Context: default
Debug Mode: false
Server:
Containers: 0
Running: 0
Paused: 0
Stopped: 0
Images: 0
Server Version: 20.10.12
Storage Driver: overlay2
Backing Filesystem: extfs
Supports d_type: true
Native Overlay Diff: true
userxattr: false
Logging Driver: json-file
Cgroup Driver: systemd
Cgroup Version: 2
Plugins:
Volume: local
Network: bridge host ipvlan macvlan null overlay
Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
Swarm: inactive
Runtimes: io.containerd.runtime.v1.linux runc io.containerd.runc.v2
Default Runtime: runc
Init Binary: docker-init
containerd version:
runc version:
init version:
Security Options:
apparmor
seccomp
Profile: default
cgroupns
Kernel Version: 5.15.0-43-generic
Operating System: Ubuntu 22.04.1 LTS
OSType: linux
Architecture: x86_64
CPUs: 2
Total Memory: 3.8GiB
Name: ubuntu2204
ID: KZWM:XV2H:TECS:YALE:RV7H:IMVK:BITA:QTRO:52DQ:POVV:WL5I:YQVO
Docker Root Dir: /var/lib/docker #默认数据根目录
Debug Mode: false
Registry: https://index.docker.io/v1/
Labels:
Experimental: false
Insecure Registries:
127.0.0.0/8
Live Restore Enabled: false
#停止Dokcer服务
root@ubuntu2204:~# sudo systemctl stop docker
Warning: Stopping docker.service, but it can still be activated by:
docker.socket
root@ubuntu2204:~# sudo systemctl stop docker.socket
root@ubuntu2204:~# sudo systemctl stop containerd
#转移 root 目录为/data/docker
root@ubuntu2204:~# mkdir -p /data/docker
root@ubuntu2204:~# mv /var/lib/docker/ /data/
#编写 daemon.json,添加如下内容
root@ubuntu2204:~# sudo vim /etc/docker/daemon.json
{
"data-root":"/data/docker/"
}
#重启docker服务
root@ubuntu2204:~# sudo systemctl start docker
root@ubuntu2204:~# docker info
Client:
Context: default
Debug Mode: false
Server:
Containers: 0
Running: 0
Paused: 0
Stopped: 0
Images: 0
Server Version: 20.10.12
Storage Driver: overlay2
Backing Filesystem: extfs
Supports d_type: true
Native Overlay Diff: true
userxattr: false
Logging Driver: json-file
Cgroup Driver: systemd
Cgroup Version: 2
Plugins:
Volume: local
Network: bridge host ipvlan macvlan null overlay
Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
Swarm: inactive
Runtimes: io.containerd.runc.v2 io.containerd.runtime.v1.linux runc
Default Runtime: runc
Init Binary: docker-init
containerd version:
runc version:
init version:
Security Options:
apparmor
seccomp
Profile: default
cgroupns
Kernel Version: 5.15.0-43-generic
Operating System: Ubuntu 22.04.1 LTS
OSType: linux
Architecture: x86_64
CPUs: 2
Total Memory: 3.8GiB
Name: ubuntu2204
ID: KZWM:XV2H:TECS:YALE:RV7H:IMVK:BITA:QTRO:52DQ:POVV:WL5I:YQVO
Docker Root Dir: /data/docker
Debug Mode: false
Registry: https://index.docker.io/v1/
Labels:
Experimental: false
Insecure Registries:
127.0.0.0/8
Live Restore Enabled: false
root@ubuntu2204:~#
添加镜像加速器如果之前有了别的定义,也写在大括号里面用逗号隔开。
root@ubuntu2204:~# vim /etc/docker/daemon.json
{
"registry-mirrors": ["https://uietgfqt.mirror.aliyuncs.com"]
}
root@ubuntu2204:~# sudo systemctl daemon-reload
root@ubuntu2204:~# sudo systemctl restart docker
root@ubuntu2204:~# sudo systemctl daemon-reload ; sudo systemctl restart docker
root@ubuntu2204:~# docker info
Client:
Context: default
Debug Mode: false
Server:
Containers: 0
Running: 0
Paused: 0
Stopped: 0
Images: 0
Server Version: 20.10.12
Storage Driver: overlay2
Backing Filesystem: extfs
Supports d_type: true
Native Overlay Diff: true
userxattr: false
Logging Driver: json-file
Cgroup Driver: systemd
Cgroup Version: 2
Plugins:
Volume: local
Network: bridge host ipvlan macvlan null overlay
Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
Swarm: inactive
Runtimes: io.containerd.runc.v2 io.containerd.runtime.v1.linux runc
Default Runtime: runc
Init Binary: docker-init
containerd version:
runc version:
init version:
Security Options:
apparmor
seccomp
Profile: default
cgroupns
Kernel Version: 5.15.0-43-generic
Operating System: Ubuntu 22.04.1 LTS
OSType: linux
Architecture: x86_64
CPUs: 2
Total Memory: 3.8GiB
Name: ubuntu2204
ID: KZWM:XV2H:TECS:YALE:RV7H:IMVK:BITA:QTRO:52DQ:POVV:WL5I:YQVO
Docker Root Dir: /data/docker
Debug Mode: false
Registry: https://index.docker.io/v1/
Labels:
Experimental: false
Insecure Registries:
127.0.0.0/8
Registry Mirrors:
https://uietgfqt.mirror.aliyuncs.com/
Live Restore Enabled: false
root@ubuntu2204:~#
root@ubuntu2204:~# cat /etc/docker/daemon.json
{
"data-root":"/data/docker/",
"registry-mirrors": ["https://uietgfqt.mirror.aliyuncs.com"]
}
root@ubuntu2204:~#
2,容器命令行CLI
2.1 容器创建
docker create
创建容器实际上就是复制image,命令docker create
用法
oot@ubuntu2204:~# docker create --help
Usage: docker create [OPTIONS] IMAGE [COMMAND] [ARG...]
Create a new container
Options:
。。。。
--name string Assign a name to the container #在创建容器时指定容器名称
示例
root@ubuntu2204:~# du -sh /data/docker/
244K /data/docker/
root@ubuntu2204:~# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
root@ubuntu2204:~# docker pull nginx
Using default tag: latest
latest: Pulling from library/nginx
a2abf6c4d29d: Pull complete
a9edb18cadd1: Pull complete
589b7251471a: Pull complete
186b1aaa4aa6: Pull complete
b4df32aa5a72: Pull complete
a0bcbecc962e: Pull complete
Digest: sha256:0d17b565c37bcbd895e9d92315a05c1c3c9a29f762b011a10c54a66cd53c9b31
Status: Downloaded newer image for nginx:latest
docker.io/library/nginx:latest
root@ubuntu2204:~# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx latest 605c77e624dd 12 months ago 141MB
root@ubuntu2204:~# docker create nginx:latest
8dd8f5328dffe3a1173cfe120fae47484ad582e1273a127916fdff8e60ff4bc8
root@ubuntu2204:~# du -sh /data/docker/
151M /data/docker/
root@ubuntu2204:~#
2.2 查看容器
docker -ps
默认显示运行状态的容器,
-a 显示所有状态的容器。
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 Don't 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
8dd8f5328dff nginx:latest "/docker-entrypoint.…" 10 minutes ago Created boring_goldstine
容器本质上进程,创建容器只是复制image,但是还没有运行起来,所以看不到进程。此时,并且数据根目录大小也没变化。
root@ubuntu2204:~# ps aux|grep nginx
root 6484 0.0 0.0 6476 2260 pts/6 S+ 12:44 0:00 grep --color=auto nginx
root@ubuntu2204:~# du -sh /data/docker
151M /data/docker
root@ubuntu2204:~# ll /data/docker/containers/
total 12
drwx--x--- 3 root root 4096 Jan 3 12:29 ./
drwx--x--- 13 root root 4096 Jan 3 12:14 ../
drwx--x--- 3 root root 4096 Jan 3 12:29 8dd8f5328dffe3a1173cfe120fae47484ad582e1273a127916fdff8e60ff4bc8/
root@ubuntu2204:~# tree /data/docker/containers/8dd8f5328dffe3a1173cfe120fae47484ad582e1273a127916fdff8e60ff4bc8/
/data/docker/containers/8dd8f5328dffe3a1173cfe120fae47484ad582e1273a127916fdff8e60ff4bc8/
├── checkpoints
├── config.v2.json
└── hostconfig.json
1 directory, 2 files
root@ubuntu2204:~#
示例:指定名字
可以通过三种方式识别容器:
2.3 启动容器
docker start
docker start 容器ID或名称
root@ubuntu2204:~# docker start --help
Usage: docker start [OPTIONS] CONTAINER [CONTAINER...]
Start one or more stopped containers
Options:
-a, --attach Attach STDOUT/STDERR and forward signals
--detach-keys string Override the key sequence for detaching a container
-i, --interactive Attach container's STDIN
root@ubuntu2204:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
8dd8f5328dff nginx:latest "/docker-entrypoint.…" 23 minutes ago Created boring_goldstine
root@ubuntu2204:~# du -sh /data/docker
151M /data/docker
root@ubuntu2204:~# docker start boring_goldstine
boring_goldstine
root@ubuntu2204:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
8dd8f5328dff nginx:latest "/docker-entrypoint.…" 23 minutes ago Up 4 seconds 80/tcp boring_goldstine
容器启动之后数据目录变大,也增加了一些文件。
root@ubuntu2204:~# du -sh /data/docker
298M /data/docker
root@ubuntu2204:~# tree /data/docker/containers/8dd8f5328dffe3a1173cfe120fae47484ad582e1273a127916fdff8e60ff4bc8/
/data/docker/containers/8dd8f5328dffe3a1173cfe120fae47484ad582e1273a127916fdff8e60ff4bc8/
├── 8dd8f5328dffe3a1173cfe120fae47484ad582e1273a127916fdff8e60ff4bc8-json.log
├── checkpoints
├── config.v2.json
├── hostconfig.json
├── hostname
├── hosts
├── mounts
├── resolv.conf
└── resolv.conf.hash
2 directories, 7 files
root@ubuntu2204:~#
root@ubuntu2204:~# ls /data/docker/volumes/
backingFsBlockDev metadata.db
root@ubuntu2204:~# ls /data/docker/
buildkit containers image network overlay2 plugins runtimes swarm tmp trust volumes
root@ubuntu2204:~# ls /data/docker/overlay2/
274af8f4099d035812b99a2d45652cd4dca273d7db9bb3d9eada764eaefd5b40 73cbb9671db1515f18bdf3e274b9cf836ff3b9c925adb438f79da63e1200c056
36980a6dd0f318d40fa2ceb48b4d27e81833c95ea89f94776c868f32bd1a34a9 8fef2c8d09ae78da14b279bc1ab1a07de713c530dd8ec53c76c5dd9573c29f11
4511584cd776f33c45876483b8cd80962695b3526cf34ffbfef9b524aa73e121 9ba8ba2a6fece861e26c40f2c3ab77806f3d9496eccc208a6b6ef19e1af9506d
4511584cd776f33c45876483b8cd80962695b3526cf34ffbfef9b524aa73e121-init l
657928bd618dd8de2b94bc3915f31eb124dde49b36a5f0c568029ec936dadac3
root@ubuntu2204:~# du -sh /data/docker/overlay2/274af8f4099d035812b99a2d45652cd4dca273d7db9bb3d9eada764eaefd5b40/
28K /data/docker/overlay2/274af8f4099d035812b99a2d45652cd4dca273d7db9bb3d9eada764eaefd5b40/
root@ubuntu2204:~# ls /data/docker/overlay2/ -t
4511584cd776f33c45876483b8cd80962695b3526cf34ffbfef9b524aa73e121 73cbb9671db1515f18bdf3e274b9cf836ff3b9c925adb438f79da63e1200c056
4511584cd776f33c45876483b8cd80962695b3526cf34ffbfef9b524aa73e121-init 8fef2c8d09ae78da14b279bc1ab1a07de713c530dd8ec53c76c5dd9573c29f11
l 657928bd618dd8de2b94bc3915f31eb124dde49b36a5f0c568029ec936dadac3
36980a6dd0f318d40fa2ceb48b4d27e81833c95ea89f94776c868f32bd1a34a9 9ba8ba2a6fece861e26c40f2c3ab77806f3d9496eccc208a6b6ef19e1af9506d
274af8f4099d035812b99a2d45652cd4dca273d7db9bb3d9eada764eaefd5b40
root@ubuntu2204:~# du -sh /data/docker/overlay2/4511584cd776f33c45876483b8cd80962695b3526cf34ffbfef9b524aa73e121
148M /data/docker/overlay2/4511584cd776f33c45876483b8cd80962695b3526cf34ffbfef9b524aa73e121
root@ubuntu2204:~#
用同一个镜像在创建一个容器,也会在复制一份镜像文件。
root@ubuntu2204:~# du -sh /data/docker/
298M /data/docker/
root@ubuntu2204:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
8dd8f5328dff nginx:latest "/docker-entrypoint.…" 31 minutes ago Up 7 minutes 80/tcp boring_goldstine
root@ubuntu2204:~# docker run nginx:latest
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2023/01/03 13:02:34 [notice] 1#1: using the "epoll" event method
2023/01/03 13:02:34 [notice] 1#1: nginx/1.21.5
2023/01/03 13:02:34 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6)
2023/01/03 13:02:34 [notice] 1#1: OS: Linux 5.15.0-43-generic
2023/01/03 13:02:34 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2023/01/03 13:02:34 [notice] 1#1: start worker processes
2023/01/03 13:02:34 [notice] 1#1: start worker process 31
2023/01/03 13:02:34 [notice] 1#1: start worker process 32 #默认前台运行,-d后台运行
root@ubuntu2204:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
be01627007fb nginx:latest "/docker-entrypoint.…" About a minute ago Up About a minute 80/tcp priceless_nightingale
8dd8f5328dff nginx:latest "/docker-entrypoint.…" 34 minutes ago Up 10 minutes 80/tcp boring_goldstine
root@ubuntu2204:~# ps axu|grep nginx
root 6576 0.0 0.1 8856 5516 ? Ss 12:53 0:00 nginx: master process nginx -g daemon off;
systemd+ 6628 0.0 0.0 9276 2672 ? S 12:53 0:00 nginx: worker process
systemd+ 6629 0.0 0.0 9276 2672 ? S 12:53 0:00 nginx: worker process
root 6655 0.0 1.2 1273784 49348 pts/6 Sl+ 13:02 0:00 docker run nginx:latest
root 6724 0.0 0.1 8856 5508 ? Ss 13:02 0:00 nginx: master process nginx -g daemon off;
systemd+ 6774 0.0 0.0 9276 2588 ? S 13:02 0:00 nginx: worker process
systemd+ 6775 0.0 0.0 9276 2588 ? S 13:02 0:00 nginx: worker process
root 6908 0.0 0.0 6608 2264 pts/8 R+ 13:08 0:00 grep --color=auto nginx
root@ubuntu2204:~# du -sh /data/docker/
445M /data/docker/
2.4 运行容器
docker run=复制image生成容器docker create+docker start,容器的创建实际上就是复制image文件。
运行容器基本命令采用以下形式:docker run ,容器创建并启动
容器必须要有一个前台运行的进程,才能不退出。
–privileged 向此容器授予扩展权限,让容器可以控制宿主机,这个比较危险,谨慎使用。
docker run [OPTIONS] IMAGE[:TAG|@DIGEST] [COMMAND] [ARG...]
#该命令必须指定要生成容器的 IMAGE。
#选项:
-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,台后运行,默认前台
--volume,-v 绑定装载卷
--rm 容器退出时自动移除容器
--publish,-p 将容器的端口发布到主机
--publish-all,-P 将所有公开的端口发布到随机端口
--env,-e 设置环境变量
示例
docker run -d -p 80:80 my_image service nginx start
#Ubuntu默认是前台运行,运行就退出,-i交互,-t分配终端
root@ubuntu2204:~# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx latest 605c77e624dd 12 months ago 141MB
ubuntu jammy 9d28ccdc1fc7 13 months ago 76.3MB
root@ubuntu2204:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
be01627007fb nginx:latest "/docker-entrypoint.…" 2 hours ago Up 9 minutes 80/tcp priceless_nightingale
root@ubuntu2204:~# docker run ubuntu:jammy
root@ubuntu2204:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
feac00c812fa ubuntu:jammy "bash" 3 seconds ago Exited (0) 3 seconds ago eager_shaw
be01627007fb nginx:latest "/docker-entrypoint.…" 2 hours ago Up 10 minutes 80/tcp priceless_nightingale
root@ubuntu2204:~#
#容器Ubuntu交互式
root@ubuntu2204:~# docker run -it ubuntu:jammy
root@52c36c5079d5:/# ls
bin boot dev etc home lib lib32 lib64 libx32 media mnt opt proc root run sbin srv sys tmp usr var
root@52c36c5079d5:/# pwd
/
root@52c36c5079d5:/#
root@52c36c5079d5:/# exit
exit
root@ubuntu2204:~#
#容器Ubuntu后台运行,-d
2.4.1 docker命令后台运行
#docker命令后台运行,-d
root@ubuntu2204:~# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
alpine 3.16.2 9c6f07244728 4 months ago 5.54MB
nginx latest 605c77e624dd 12 months ago 141MB
ubuntu jammy 9d28ccdc1fc7 13 months ago 76.3MB
root@ubuntu2204:~# docker run -d alpine:3.16.2 sleep 100
b7788f0d576400168d52c2b748ae3aad0b900ac729db4e576a4ad2d21781005f
root@ubuntu2204:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b7788f0d5764 alpine:3.16.2 "sleep 100" 14 seconds ago Up 12 seconds thirsty_williamson
52c36c5079d5 ubuntu:jammy "bash" 11 hours ago Up 5 minutes compassionate_albattani
be01627007fb nginx:latest "/docker-entrypoint.…" 13 hours ago Up 14 minutes 80/tcp priceless_nightingale
root@ubuntu2204:~#
2.4.1 暴露所有容器端口
容器启动后,默认处于预定义的NAT网络中,所以外部网络的主机无法直接访问容器中网络服务
docker run -P 可以将事先容器预定义的所有端口映射宿主机的网卡的随机端口,默认从32768开始
使用随机端口 时,当停止容器后再启动可能会导致端口发生变化
-P , --publish-all= true | false默认为false
#示例:
docker run -P docker.io/nginx #映射容器所有暴露端口至随机本地端口
在启动容器的时候是分配给容器唯一的IP。这个IP地址实际上是和docker0桥接一起的。
root@ubuntu2204:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
52c36c5079d5 ubuntu:jammy "bash" 11 hours ago Up 13 minutes compassionate_albattani
be01627007fb nginx:latest "/docker-entrypoint.…" 13 hours ago Up 22 minutes 80/tcp priceless_nightingale
root@ubuntu2204:~# docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' priceless_nightingale
172.17.0.2
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: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
link/ether 00:0c:29:2a:fe:f9 brd ff:ff:ff:ff:ff:ff
altname enp2s1
inet 10.0.0.223/24 brd 10.0.0.255 scope global ens33
valid_lft forever preferred_lft forever
inet6 fe80::20c:29ff:fe2a:fef9/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:98:82:64:b1 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:98ff:fe82:64b1/64 scope link
valid_lft forever preferred_lft forever
5: vethe3a719b@if4: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker0 state UP group default #这是虚拟网卡,对应其中一个运行的容器,并与docker0桥接
link/ether 62:75:cb:7d:cc:13 brd ff:ff:ff:ff:ff:ff link-netnsid 0
inet6 fe80::6075:cbff:fe7d:cc13/64 scope link
valid_lft forever preferred_lft forever
15: vethbf57483@if14: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker0 state UP group default #这是虚拟网卡,对应其中一个运行的容器,成对出现,并与docker0桥接
link/ether 82:b6:84:3a:96:5c brd ff:ff:ff:ff:ff:ff link-netnsid 1
inet6 fe80::80b6:84ff:fe3a:965c/64 scope link
valid_lft forever preferred_lft forever
进入容器查看Ip容器IP地址
root@ubuntu2204:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
52c36c5079d5 ubuntu:jammy "bash" 11 hours ago Up 21 minutes compassionate_albattani
be01627007fb nginx:latest "/docker-entrypoint.…" 13 hours ago Up 30 minutes 80/tcp priceless_nightingale
root@ubuntu2204:~# docker exec -it 52c36c5079d5 bash
root@52c36c5079d5:/# ip a
bash: ip: command not found
root@52c36c5079d5:/# apt update
Get:1 http://archive.ubuntu.com/ubuntu jammy InRelease [270 kB]
Get:2 http://security.ubuntu.com/ubuntu jammy-security InRelease [110 kB]
Get:3 http://archive.ubuntu.com/ubuntu jammy-updates InRelease [114 kB]
Get:4 http://security.ubuntu.com/ubuntu jammy-security/multiverse amd64 Packages [4732 B]
Get:5 http://archive.ubuntu.com/ubuntu jammy-backports InRelease [99.8 kB]
Get:6 http://security.ubuntu.com/ubuntu jammy-security/main amd64 Packages [667 kB]
Get:7 http://archive.ubuntu.com/ubuntu jammy/universe amd64 Packages [17.5 MB]
Get:8 http://security.ubuntu.com/ubuntu jammy-security/restricted amd64 Packages [593 kB]
Get:9 http://security.ubuntu.com/ubuntu jammy-security/universe amd64 Packages [781 kB]
Get:10 http://archive.ubuntu.com/ubuntu jammy/multiverse amd64 Packages [266 kB]
Get:11 http://archive.ubuntu.com/ubuntu jammy/restricted amd64 Packages [164 kB]
Get:12 http://archive.ubuntu.com/ubuntu jammy/main amd64 Packages [1792 kB]
Get:13 http://archive.ubuntu.com/ubuntu jammy-updates/restricted amd64 Packages [641 kB]
Get:14 http://archive.ubuntu.com/ubuntu jammy-updates/universe amd64 Packages [973 kB]
Get:15 http://archive.ubuntu.com/ubuntu jammy-updates/main amd64 Packages [977 kB]
Get:16 http://archive.ubuntu.com/ubuntu jammy-updates/multiverse amd64 Packages [8150 B]
Get:17 http://archive.ubuntu.com/ubuntu jammy-backports/main amd64 Packages [3520 B]
Get:18 http://archive.ubuntu.com/ubuntu jammy-backports/universe amd64 Packages [7291 B]
Fetched 24.9 MB in 1min 20s (312 kB/s)
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
94 packages can be upgraded. Run 'apt list --upgradable' to see them.
root@52c36c5079d5:/# apt install -y net-tools
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following NEW packages will be installed:
net-tools
0 upgraded, 1 newly installed, 0 to remove and 94 not upgraded.
Need to get 204 kB of archives.
After this operation, 819 kB of additional disk space will be used.
Get:1 http://archive.ubuntu.com/ubuntu jammy/main amd64 net-tools amd64 1.60+git20181103.0eebece-1ubuntu5 [204 kB]
Fetched 204 kB in 2s (119 kB/s)
debconf: delaying package configuration, since apt-utils is not installed
Selecting previously unselected package net-tools.
(Reading database ... 4384 files and directories currently installed.)
Preparing to unpack .../net-tools_1.60+git20181103.0eebece-1ubuntu5_amd64.deb ...
Unpacking net-tools (1.60+git20181103.0eebece-1ubuntu5) ...
Setting up net-tools (1.60+git20181103.0eebece-1ubuntu5) ...
root@52c36c5079d5:/# ip a
bash: ip: command not found
root@52c36c5079d5:/# ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 172.17.0.3 netmask 255.255.0.0 broadcast 172.17.255.255
ether 02:42:ac:11:00:03 txqueuelen 0 (Ethernet)
RX packets 8778 bytes 25626708 (25.6 MB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 8759 bytes 477437 (477.4 KB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
loop txqueuelen 1000 (Local Loopback)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
root@52c36c5079d5:/# hostname -I
172.17.0.3
root@52c36c5079d5:/# exit
exit
进入nginx容器修改首页,并通过容器ip本机访问。
那么问题来了,容器是隔离的,那么不同的宿主机的容器IP地址一样会怎么样?默认容器IP不支持夸宿主机,只支持本机访问或本宿主机内其他容器进行访问,所以需要进行暴露。
root@ubuntu2204:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
52c36c5079d5 ubuntu:jammy "bash" 11 hours ago Up 27 minutes compassionate_albattani
be01627007fb nginx:latest "/docker-entrypoint.…" 13 hours ago Up 36 minutes 80/tcp priceless_nightingale
root@ubuntu2204:~# docker exec -it priceless_nightingale bash
root@be01627007fb:/# hostname -I
172.17.0.2
root@be01627007fb:/# ls /usr/share/nginx/html
50x.html index.html
root@be01627007fb:/# echo "docker site" > /usr/share/nginx/html/index.html
root@be01627007fb:/#
root@ubuntu2204:~# curl 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:~# curl 172.17.0.2
docker site
root@ubuntu2204:~#
桥接模式:
宿主机里不同容器进行访问,宿主机与容器访问。容器自身可以访互联网,但是外面的访问不了容器,也不支持跨宿主机访问。
root@ubuntu2204:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
52c36c5079d5 ubuntu:jammy "bash" 12 hours ago Up 40 minutes compassionate_albattani
be01627007fb nginx:latest "/docker-entrypoint.…" 13 hours ago Up 49 minutes 80/tcp priceless_nightingale
root@ubuntu2204:~# docker exec -it priceless_nightingale bash #容器Ubuntu
root@be01627007fb:/# hostname -I
172.17.0.2
root@be01627007fb:/# exit
exit
root@ubuntu2204:~# docker exec -it compassionate_albattani bash #容器nginx
root@52c36c5079d5:/# hostname -i
172.17.0.3
root@52c36c5079d5:/# curl 172.17.0.2
bash: curl: command not found
root@52c36c5079d5:/# apt update ,apt -y install curl
root@52c36c5079d5:/# curl 172.17.0.2
docker site
root@52c36c5079d5:/# curl www.baidu.com #容器自身可以访互联网
<!DOCTYPE html>
<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn"></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=http://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');</script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>©2017 Baidu <a href=http://www.baidu.com/duty/>使用百度前必读</a> <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a> 京ICP证030173号 <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>
root@52c36c5079d5:/# exit
exit
root@ubuntu2204:~# curl 172.17.0.2
docker site
root@ubuntu2204:~#
暴露所有容器端口,解决容器跨宿主机和互联网访问问题,也就是DNAT端口映射,也就是将容器的端口映射到宿主机的随机端口,底层就是IPtable规则。DNAT 172.17.02.2:80—>10.0.0.223:XXXX
docker run -p
root@ubuntu2204:~# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
alpine 3.16.2 9c6f07244728 4 months ago 5.54MB
nginx latest 605c77e624dd 12 months ago 141MB
ubuntu jammy 9d28ccdc1fc7 13 months ago 76.3MB
root@ubuntu2204:~# docker inspect nginx | grep -i -C 10 port #容器nginx默认端口80
暴露所有容器端口给宿主机
##自动生成Iptables规则
2.4.2 查看容器的端口映射关系
docker port
root@ubuntu2204:~# docker port --help
Usage: docker port CONTAINER [PRIVATE_PORT[/PROTO]]
List port mappings or a specific mapping for the container
root@ubuntu2204:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
244d75284320 nginx "/docker-entrypoint.…" 2 minutes ago Up 2 minutes 0.0.0.0:49154->80/tcp, :::49154->80/tcp magical_hertz
52c36c5079d5 ubuntu:jammy "bash" 12 hours ago Up About an hour compassionate_albattani
be01627007fb nginx:latest "/docker-entrypoint.…" 14 hours ago Up About an hour 80/tcp priceless_nightingale
root@ubuntu2204:~# docker port magical_hertz
80/tcp -> 0.0.0.0:49154
80/tcp -> :::49154
root@ubuntu2204:~#
测试跨主机访问
root@ubuntu2204:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
244d75284320 nginx "/docker-entrypoint.…" 9 minutes ago Up 9 minutes 0.0.0.0:49154->80/tcp, :::49154->80/tcp magical_hertz
52c36c5079d5 ubuntu:jammy "bash" 12 hours ago Up About an hour compassionate_albattani
be01627007fb nginx:latest "/docker-entrypoint.…" 14 hours ago Up About an hour 80/tcp priceless_nightingale
root@ubuntu2204:~# docker exec -it magical_hertz bash
root@244d75284320:/# hostname -I
172.17.0.4
root@244d75284320:/# echo "2023 happy new years!" > /usr/share/nginx/html/index.html
root@244d75284320:/# exit
exit
root@ubuntu2204:~# hostname -I
10.0.0.223 172.17.0.1
root@ubuntu2204:~#
[root@Rocky8 ~]# curl 10.0.0.223:49154
2023 happy new years!
[root@Rocky8 ~]# hostname -I
10.0.0.202 172.17.0.1
[root@Rocky8 ~]#
2.4.3 指定容器端口映射
docker run -p
可以将容器的预定义的指定端口映射到宿主机的相应端口
注意: 多个容器映射到宿主机的端口不能冲突,但容器内使用的端口可以相同
root@ubuntu2204:~# ss -ntl
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 4096 127.0.0.1:38379 0.0.0.0:*
LISTEN 0 4096 127.0.0.53%lo:53 0.0.0.0:*
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 127.0.0.1:6010 0.0.0.0:*
LISTEN 0 128 127.0.0.1:6011 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
LISTEN 0 128 [::1]:6010 [::]:*
LISTEN 0 128 [::1]:6011 [::]:*
root@ubuntu2204:~#
root@ubuntu2204:~# rmall
244d75284320
ffbb61c5623c
b7788f0d5764
2d16054c17da
52c36c5079d5
feac00c812fa
be01627007fb
root@ubuntu2204:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
root@ubuntu2204:~# alias rmall
alias rmall='docker ps -a -q | xargs docker rm -f'
#前一个80是宿主机空闲端口,后一个80是容器的端口,注意宿主机端口不能冲突。
root@ubuntu2204:~# docker run -d --name web01 -p 80:80 nginx
48f247f46cabf5c1c7d154c9976f80d96a3405c8b207cdefbe883a73cd312dd3
root@ubuntu2204:~# docker port
"docker port" requires at least 1 and at most 2 arguments.
See 'docker port --help'.
Usage: docker port CONTAINER [PRIVATE_PORT[/PROTO]]
List port mappings or a specific mapping for the container
root@ubuntu2204:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
48f247f46cab nginx "/docker-entrypoint.…" 31 seconds ago Up 30 seconds 0.0.0.0:80->80/tcp, :::80->80/tcp web01
root@ubuntu2204:~# docker port web01
80/tcp -> 0.0.0.0:80
80/tcp -> :::80
root@ubuntu2204:~#
root@ubuntu2204:~# docker run -d --name web02 -p 8888:80 nginx
a8626bc922618b71a5cde9f358f464c3c118c02601239f06805a41ccab6e108f
root@ubuntu2204:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
a8626bc92261 nginx "/docker-entrypoint.…" 7 seconds ago Up 6 seconds 0.0.0.0:8888->80/tcp, :::8888->80/tcp web02
48f247f46cab nginx "/docker-entrypoint.…" 4 minutes ago Up 4 minutes 0.0.0.0:80->80/tcp, :::80->80/tcp web01
root@ubuntu2204:~# hostname -I
10.0.0.223 172.17.0.1
#测试跨主机访问
```bash
[root@Rocky8 ~]# curl 10.0.0.223:49154
2023 happy new years!
[root@Rocky8 ~]# hostname -I
10.0.0.202 172.17.0.1
[root@Rocky8 ~]#
[root@Rocky8 ~]# curl 10.0.0.223:80
<!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@Rocky8 ~]# curl 10.0.0.223:8888
<!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@Rocky8 ~]#
```bash
方式1: 容器80端口映射宿主机本地随机端口
docker run -p 80 --name nginx-test-port1 nginx
方式2: 容器80端口映射到宿主机本地端口81
docker run -p 81:80 --name nginx-test-port2 nginx
方式3: 宿主机本地IP:宿主机本地端口:容器端口
docker run -p 10.0.0.100:82:80 --name nginx-test-port3 docker.io/nginx
方式4: 宿主机本地IP:宿主机本地随机端口:容器端口,默认从32768开始
docker run -p 10.0.0.100::80 --name nginx-test-port4 docker.io/nginx
方式5: 宿主机本机ip:宿主机本地端口:容器端口/协议,默认为tcp协议
docker run -p 10.0.0.100:83:80/udp --name nginx-test-port5 docker.io/nginx
方式6: 一次性映射多个端口+协议
docker run -p 8080:80/tcp -p 8443:443/tcp -p 53:53/udp --name nginx-test-port6
nginx
2.4.4 传递运行命令
容器需要有一个前台运行的进程才能保持容器的运行,通过传递运行参数是一种方式,另外也可以在构建镜像的时候指定容器启动时运行的前台命令
root@ubuntu2204:~# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
alpine 3.16.2 9c6f07244728 4 months ago 5.54MB
nginx latest 605c77e624dd 12 months ago 141MB
ubuntu jammy 9d28ccdc1fc7 13 months ago 76.3MB
alpine latest c059bfaa849c 13 months ago 5.59MB
root@ubuntu2204:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
root@ubuntu2204:~# docker run -d alpine:3.16.2 #alpine是sh默认没有前台运行进程,所以容器起不来
fbbcaa8492cbf93255c0883d6e5a45ea54009d0272cb8ca573636bc1d5ea96d3
root@ubuntu2204:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
root@ubuntu2204:~# docker run -d alpine:3.16.2 ls #指定一个目前不能运行的命令,也起不来
8275ebb9926dacf39cf757fef87f61a20120b24e651c69973ec26fada0a656c9
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
8275ebb9926d alpine:3.16.2 "ls" 21 seconds ago Exited (0) 20 seconds ago flamboyant_cannon
fbbcaa8492cb alpine:3.16.2 "/bin/sh" 57 seconds ago Exited (0) 57 seconds ago zealous_mcnulty
root@ubuntu2204:~# docker run -d alpine:3.16.2 tail -f /etc/hosts #指定一个可以运行的命令,也就是有了一个前台进程,并且这个命令不能退出,退出也不行了。
81e0f88980978aa7f7926b15fba20d4801d1b81e47b86f6bc6c6ea6e0651d7bb
root@ubuntu2204:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
81e0f8898097 alpine:3.16.2 "tail -f /etc/hosts" 4 seconds ago Up 3 seconds eager_lalande
root@ubuntu2204:~#
2.4.5 设置自定义 DNS 服务器
容器的dns服务器,默认采用宿主机的dns 地址,可以用下面方式指定其它的DNS地址
将dns地址配置在宿主机
在容器启动时加选项 --dns=x.x.x.x
在/etc/docker/daemon.json 文件中指定
--dns 设置自定义 DNS 服务器
--dns-opt 设置 DNS 选项
--dns-option 设置 DNS 选项
--dns-search 设置自定义 DNS 搜索域
容器默认DNS是用的宿主的
root@ubuntu2204:~# docker exec -it eager_lalande
"docker exec" requires at least 2 arguments.
See 'docker exec --help'.
Usage: docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
Run a command in a running container
root@ubuntu2204:~# docker exec -it eager_lalande sh
/ # 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 you're 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 #容器默认DNS是用的宿主的
nameserver 223.6.6.6
search guobao-liu.com
/ #
root@ubuntu2204:~# resolvectl status
Global
Protocols: -LLMNR -mDNS -DNSOverTLS DNSSEC=no/unsupported
resolv.conf mode: stub
Link 2 (ens33)
Current Scopes: DNS
Protocols: +DefaultRoute +LLMNR -mDNS -DNSOverTLS DNSSEC=no/unsupported
Current DNS Server: 223.6.6.6
DNS Servers: 180.76.76.76 223.6.6.6
DNS Domain: guobao-liu.com
Link 3 (docker0)
Current Scopes: none
Protocols: -DefaultRoute +LLMNR -mDNS -DNSOverTLS DNSSEC=no/unsupported
Link 39 (vethaf4e793)
Current Scopes: none
Protocols: -DefaultRoute +LLMNR -mDNS -DNSOverTLS DNSSEC=no/unsupported
root@ubuntu2204:~#
指定DNS
root@ubuntu2204:~# docker run -d --name web008 --dns 8.8.8.8 alpine:3.16.2 sleep 100
f0d7c80cb79fcbfb569b259b53976d4e62acbd5831bdb117d0574a14e4492b4c
root@ubuntu2204:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
f0d7c80cb79f alpine:3.16.2 "sleep 100" 5 seconds ago Up 4 seconds web008
81e0f8898097 alpine:3.16.2 "tail -f /etc/hosts" About an hour ago Up About an hour eager_lalande
root@ubuntu2204:~# docker exec -it web008 sh
/ # cat /etc/resolv.conf
search guobao-liu.com
nameserver 8.8.8.8
/ #
2.4.6 传递环境变量
有些容器运行时,需要传递变量,可以使用 -e <参数> 或 --env-file <参数文件> 实现
--env,-e 设置环境变量
--env-file 读入环境变量文件
root@ubuntu2204:~# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
alpine 3.16.2 9c6f07244728 4 months ago 5.54MB
nginx latest 605c77e624dd 12 months ago 141MB
ubuntu jammy 9d28ccdc1fc7 13 months ago 76.3MB
alpine latest c059bfaa849c 13 months ago 5.59MB
mysql 5.7.32 cc8775c0fe94 24 months ago 449MB
root@ubuntu2204:~# 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.32
04e5f5f9ee9fccc48cb2c70b649e50e7b56547b1e711fb37b1ff58ea818c31f8
root@ubuntu2204:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
04e5f5f9ee9f mysql:5.7.32 "docker-entrypoint.s…" 11 seconds ago Up 10 seconds 0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp mysql-test1
2.5 停止容器
docker stop
docker stop 容器名称或ID
root@ubuntu2204:~# docker stop --help
Usage: docker stop [OPTIONS] CONTAINER [CONTAINER...]
Stop one or more running containers
Options:
-t, --time int Seconds to wait for stop before killing it (default 10)
root@ubuntu2204:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
be01627007fb nginx:latest "/docker-entrypoint.…" 9 minutes ago Up 9 minutes 80/tcp priceless_nightingale
8dd8f5328dff nginx:latest "/docker-entrypoint.…" 42 minutes ago Up 18 minutes 80/tcp boring_goldstine
root@ubuntu2204:~# du -sh /data/docker/
445M /data/docker/
root@ubuntu2204:~# ps axu|grep nginx
root 6576 0.0 0.1 8856 5516 ? Ss 12:53 0:00 nginx: master process nginx -g daemon off;
systemd+ 6628 0.0 0.0 9276 2672 ? S 12:53 0:00 nginx: worker process
systemd+ 6629 0.0 0.0 9276 2672 ? S 12:53 0:00 nginx: worker process
root 6655 0.0 1.2 1273784 49348 pts/6 Sl+ 13:02 0:00 docker run nginx:latest
root 6724 0.0 0.1 8856 5508 ? Ss 13:02 0:00 nginx: master process nginx -g daemon off;
systemd+ 6774 0.0 0.0 9276 2588 ? S 13:02 0:00 nginx: worker process
systemd+ 6775 0.0 0.0 9276 2588 ? S 13:02 0:00 nginx: worker process
root 6908 0.0 0.0 6608 2264 pts/8 R+ 13:08 0:00 grep --color=auto nginx
root@ubuntu2204:~# docker stop boring_goldstine
boring_goldstine
root@ubuntu2204:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
be01627007fb nginx:latest "/docker-entrypoint.…" 10 minutes ago Up 10 minutes 80/tcp priceless_nightingale
8dd8f5328dff nginx:latest "/docker-entrypoint.…" 43 minutes ago Exited (0) 5 seconds ago boring_goldstine
root@ubuntu2204:~# du -sh /data/docker/
298M /data/docker/
root@ubuntu2204:~#
root@ubuntu2204:~# ps axuf|grep nginx
root 6655 0.0 1.2 1273784 49348 pts/6 Sl+ 13:02 0:00 | \_ docker run nginx:latest
root 6981 0.0 0.0 6476 2368 pts/8 S+ 13:14 0:00 \_ grep --color=auto nginx
root 6724 0.0 0.1 8856 5508 ? Ss 13:02 0:00 \_ nginx: master process nginx -g daemon off;
systemd+ 6774 0.0 0.0 9276 2588 ? S 13:02 0:00 \_ nginx: worker process
systemd+ 6775 0.0 0.0 9276 2588 ? S 13:02 0:00 \_ nginx: worker process
root@ubuntu2204:~#
2.6 显示容器详细信息
docker inspect 容器ID或名称
docker inspect [OPTIONS] NAME|ID [NAME|ID...]
#选项:
--format,-f 使用给定的 Go 模板格式化输出
--size,-s 如果类型为容器,则显示总文件大小
--type 返回指定类型的 JSON
root@ubuntu2204:~# docker inspect 8dd8f5328dff
[
{
"Id": "8dd8f5328dffe3a1173cfe120fae47484ad582e1273a127916fdff8e60ff4bc8",
"Created": "2023-01-03T12:29:42.549697924Z",
"Path": "/docker-entrypoint.sh",
"Args": [
"nginx",
"-g",
"daemon off;"
],
"State": {
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 7052,
"ExitCode": 0,
"Error": "",
"StartedAt": "2023-01-03T13:20:19.091668644Z",
"FinishedAt": "2023-01-03T13:12:56.426505775Z"
},
"Image": "sha256:605c77e624ddb75e6110f997c58876baa13f8754486b461117934b24a9dc3a85",
"ResolvConfPath": "/data/docker/containers/8dd8f5328dffe3a1173cfe120fae47484ad582e1273a127916fdff8e60ff4bc8/resolv.conf",
"HostnamePath": "/data/docker/containers/8dd8f5328dffe3a1173cfe120fae47484ad582e1273a127916fdff8e60ff4bc8/hostname",
"HostsPath": "/data/docker/containers/8dd8f5328dffe3a1173cfe120fae47484ad582e1273a127916fdff8e60ff4bc8/hosts",
"LogPath": "/data/docker/containers/8dd8f5328dffe3a1173cfe120fae47484ad582e1273a127916fdff8e60ff4bc8/8dd8f5328dffe3a1173cfe120fae47484ad582e1273a127916fdff8e60ff4bc8-json.log",
"Name": "/boring_goldstine",
"RestartCount": 0,
"Driver": "overlay2",
"Platform": "linux",
"MountLabel": "",
"ProcessLabel": "",
"AppArmorProfile": "docker-default",
"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": "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/4511584cd776f33c45876483b8cd80962695b3526cf34ffbfef9b524aa73e121-init/diff:/data/docker/overlay2/36980a6dd0f318d40fa2ceb48b4d27e81833c95ea89f94776c868f32bd1a34a9/diff:/data/docker/overlay2/274af8f4099d035812b99a2d45652cd4dca273d7db9bb3d9eada764eaefd5b40/diff:/data/docker/overlay2/73cbb9671db1515f18bdf3e274b9cf836ff3b9c925adb438f79da63e1200c056/diff:/data/docker/overlay2/8fef2c8d09ae78da14b279bc1ab1a07de713c530dd8ec53c76c5dd9573c29f11/diff:/data/docker/overlay2/657928bd618dd8de2b94bc3915f31eb124dde49b36a5f0c568029ec936dadac3/diff:/data/docker/overlay2/9ba8ba2a6fece861e26c40f2c3ab77806f3d9496eccc208a6b6ef19e1af9506d/diff",
"MergedDir": "/data/docker/overlay2/4511584cd776f33c45876483b8cd80962695b3526cf34ffbfef9b524aa73e121/merged",
"UpperDir": "/data/docker/overlay2/4511584cd776f33c45876483b8cd80962695b3526cf34ffbfef9b524aa73e121/diff",
"WorkDir": "/data/docker/overlay2/4511584cd776f33c45876483b8cd80962695b3526cf34ffbfef9b524aa73e121/work"
},
"Name": "overlay2"
},
"Mounts": [],
"Config": {
"Hostname": "8dd8f5328dff",
"Domainname": "",
"User": "",
"AttachStdin": false,
"AttachStdout": true,
"AttachStderr": true,
"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.21.5",
"NJS_VERSION=0.7.1",
"PKG_RELEASE=1~bullseye"
],
"Cmd": [
"nginx",
"-g",
"daemon off;"
],
"Image": "nginx:latest",
"Volumes": null,
"WorkingDir": "",
"Entrypoint": [
"/docker-entrypoint.sh"
],
"OnBuild": null,
"Labels": {
"maintainer": "NGINX Docker Maintainers <docker-maint@nginx.com>"
},
"StopSignal": "SIGQUIT"
},
"NetworkSettings": {
"Bridge": "",
"SandboxID": "05389c5d1f5e6a7fe88838442da81626c50db88cebb6d4c11c1dd4c0c7a5cd0f",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {
"80/tcp": null
},
"SandboxKey": "/var/run/docker/netns/05389c5d1f5e",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "c80f574e4fe6ca65ce1063ea8353854c15628b126089b90b58f90f7bb6f972af",
"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": "06fe4914ddcffab98dce8afbdb406073378aa13093a477d67726b06400e491db",
"EndpointID": "c80f574e4fe6ca65ce1063ea8353854c15628b126089b90b58f90f7bb6f972af",
"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:~#
容器文件=image文件+容器自身文件,“UpperDir”+“LowerDir”=“MergedDir”,“WorkDir”:临时生成数据存放目录。
root@ubuntu2204:~# du -sh /data/docker/overlay2/4511584cd776f33c45876483b8cd80962695b3526cf34ffbfef9b524aa73e121/merged
148M /data/docker/overlay2/4511584cd776f33c45876483b8cd80962695b3526cf34ffbfef9b524aa73e121/merged
root@ubuntu2204:~# du -sh /data/docker/overlay2/4511584cd776f33c45876483b8cd80962695b3526cf34ffbfef9b524aa73e121/diff
80K /data/docker/overlay2/4511584cd776f33c45876483b8cd80962695b3526cf34ffbfef9b524aa73e121/diff
root@ubuntu2204:~# du -sh /data/docker/overlay2/4511584cd776f33c45876483b8cd80962695b3526cf34ffbfef9b524aa73e121/work
8.0K /data/docker/overlay2/4511584cd776f33c45876483b8cd80962695b3526cf34ffbfef9b524aa73e121/work
root@ubuntu2204:~# ls /data/docker/overlay2/4511584cd776f33c45876483b8cd80962695b3526cf34ffbfef9b524aa73e121/work
work
root@ubuntu2204:~#
示例:查看容器地址,每个容器都有自己的地址
root@ubuntu2204:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
be01627007fb nginx:latest "/docker-entrypoint.…" 38 minutes ago Up 38 minutes 80/tcp priceless_nightingale
8dd8f5328dff nginx:latest "/docker-entrypoint.…" About an hour ago Up 20 minutes 80/tcp boring_goldstine
#获取实例的 IP 地址
root@ubuntu2204:~# docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' boring_goldstine
172.17.0.2
#获取实例的 MAC 地址
root@ubuntu2204:~# docker inspect --format='{{range .NetworkSettings.Networks}}{{.MacAddress}}{{end}}' boring_goldstine
02:42:ac:11:00:02
#获取实例的日志路径
root@ubuntu2204:~# docker inspect --format='{{.LogPath}}' boring_goldstine
/data/docker/containers/8dd8f5328dffe3a1173cfe120fae47484ad582e1273a127916fdff8e60ff4bc8/8dd8f5328dffe3a1173cfe120fae47484ad582e1273a127916fdff8e60ff4bc8-json.log
#获取实例的镜像名称
root@ubuntu2204:~# docker inspect --format='{{.Config.Image}}' boring_goldstine
nginx:latest
#列出所有端口绑定
root@ubuntu2204:~# docker inspect --format='{{range $p, $conf := .NetworkSettings.Ports}} {{$p}} -> {{(index $conf 0).HostPort}} {{end}}' boring_goldstine
Template parsing error: template: :1:59: executing "" at <index $conf 0>: error calling index: index of untyped nil
root@ubuntu2204:~#
2.7 删除容器
删除容器意味着容器对应的所有文件将被清理。
docker rm
docker rm [OPTIONS] CONTAINER [CONTAINER...]
#选项:
--force,-f 强制删除正在运行的容器(使用 SIGKILL)
--link,-l 删除指定的链接
--volumes,-v 删除与容器关联的匿名卷
示例:强制移除正在运行的容器
root@ubuntu2204:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
be01627007fb nginx:latest "/docker-entrypoint.…" 53 minutes ago Up 53 minutes 80/tcp priceless_nightingale
8dd8f5328dff nginx:latest "/docker-entrypoint.…" About an hour ago Up 35 minutes 80/tcp boring_goldstine
root@ubuntu2204:~# docker rm 8dd8f5328dff
Error response from daemon: You cannot remove a running container 8dd8f5328dffe3a1173cfe120fae47484ad582e1273a127916fdff8e60ff4bc8. Stop the container before attempting removal or force remove
root@ubuntu2204:~# docker rm -f 8dd8f5328dff
8dd8f5328dff
root@ubuntu2204:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
be01627007fb nginx:latest "/docker-entrypoint.…" 54 minutes ago Up 54 minutes 80/tcp priceless_nightingale
root@ubuntu2204:~#
示例:删除所有 已停止的容器
root@ubuntu2204:~# docker rm $(docker ps --filter status=exited -q)
root@ubuntu2204:~# docker container prune -f
示例:删除所有容器
root@ubuntu2204:~# docker ps -a -q | xargs docker rm -f
2.8 终止正在运行容器
docker kill
终止一个或多个正在运行的容器
docker kill [OPTIONS] CONTAINER [CONTAINER...]
--signal,-s KILL 发送到容器的信号
示例:强制关闭所有运行中的容器
[root@ubuntu2204 ~]#docker kill `docker ps -a -q`
dd002f947cbe
1f3f82995e05
2.9 进入容器
docker attach
docker attach 容器名,attach 类似于vnc,操作会在同一个容器的多个会话界面同步显示,所有使用此方式进入容器的操作都是同步显示的,且使用exit退出后容器自动关闭,不推荐使用,需要进入到有shell环境的容器
#同时在第二个终端attach到同一个容器,执行命令,可以在前一终端看到显示图面是同步的
docker attach [OPTIONS] CONTAINER
#选项:
--detach-keys 覆盖用于分离容器的键序列
--no-stdin 不要附加标准丁
--sig-proxy true 将所有接收到的信号代理到进程
root@ubuntu2204:~# docker attach priceless_nightingale
pwd
ls
host^H^H^C2023/01/03 14:28:03 [notice] 1#1: signal 2 (SIGINT) received, exiting
2023/01/03 14:28:03 [notice] 25#25: exiting
2023/01/03 14:28:03 [notice] 25#25: exit
2023/01/03 14:28:03 [notice] 24#24: exiting
2023/01/03 14:28:03 [notice] 24#24: exit
2023/01/03 14:28:03 [notice] 1#1: signal 17 (SIGCHLD) received from 25
2023/01/03 14:28:03 [notice] 1#1: worker process 25 exited with code 0
2023/01/03 14:28:03 [notice] 1#1: signal 29 (SIGIO) received
2023/01/03 14:28:03 [notice] 1#1: signal 17 (SIGCHLD) received from 24
2023/01/03 14:28:03 [notice] 1#1: worker process 24 exited with code 0
2023/01/03 14:28:03 [notice] 1#1: exit
#ctrl+p+q 退出
docker exec
在正在运行的容器中运行命令
在运行中的容器启动新进程,可以执行单次命令,以及进入容器
测试环境使用此方式,使用exit退出,但容器还在运行,此为推荐方式
docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
#选项
--detach,-d 分离模式:在后台运行命令
--detach-keys 覆盖用于分离容器的键序列
--env,-e 设置环境变量
--env-file 读入环境变量文件
--interactive,-i 即使未连接,也保持 STDIN 打开
--privileged 为命令授予扩展权限
--tty,-t 分配伪 TTY
--user,-u 用户名或 UID (格式: <名称|uid>[:<group|gid>])
--workdir,-w 容器内的工作目录
在容器上执行交互式 shell,一次性任务
root@ubuntu2204:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
2d16054c17da ubuntu:jammy "bash" 7 minutes ago Exited (130) 7 minutes ago epic_solomon
52c36c5079d5 ubuntu:jammy "bash" 13 minutes ago Exited (0) 12 minutes ago compassionate_albattani
feac00c812fa ubuntu:jammy "bash" 15 minutes ago Exited (0) 15 minutes ago eager_shaw
be01627007fb nginx:latest "/docker-entrypoint.…" 2 hours ago Up 10 seconds 80/tcp priceless_nightingale
root@ubuntu2204:~# docker exec priceless_nightingale 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@ubuntu2204:~#
进入容器终端执行命令,-it分配终端,bash指定命令解释器(有时候也是sh)
root@ubuntu2204:~# docker exec -it priceless_nightingale bash
root@be01627007fb:/# 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@be01627007fb:/# ls /etc
adduser.conf cron.daily fonts host.conf ld.so.cache mke2fs.conf pam.conf rc2.d security subuid
alternatives debconf.conf fstab hostname ld.so.conf motd pam.d rc3.d selinux systemd
apt debian_version gai.conf hosts ld.so.conf.d mtab passwd rc4.d shadow terminfo
bash.bashrc default group init.d libaudit.conf netconfig passwd- rc5.d shadow- timezone
bindresvport.blacklist deluser.conf group- inputrc localtime nginx profile rc6.d shells ucf.conf
ca-certificates dpkg gshadow issue login.defs nsswitch.conf profile.d rcS.d skel update-motd.d
ca-certificates.conf e2scrub.conf gshadow- issue.net logrotate.d opt rc0.d resolv.conf ssl xattr.conf
cron.d environment gss kernel machine-id os-release rc1.d rmt subgid
root@be01627007fb:/# exit
exit
root@ubuntu2204:~#
2.10 查看容器日志
docker logs
docker logs 可以查看容器中运行的进程在控制台输出的日志信息
[root@Rocky8 ~]# 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@Rocky8 ~]#
#选项
--details 显示提供给日志的其他详细信息
--follow,-f 跟踪日志输出
--since 显示自时间戳(例如 2013-01-02T13:23:37Z)或相对(例如 42m 表示 42 分钟)以来的日志
--tail,-n all 从日志末尾显示的行数
--timestamps,-t 显示时间戳
--until 在时间戳(例如 2013-01-02T13:23:37Z)或相对时间戳(例如 42m 表示 42 分钟)之前显示日志
root@ubuntu2204:~# docker run -d -it nginx
95b0a380b6a80edbb898bfefc43471dfc42bfb5005d8c34c2de064d451603a05
root@ubuntu2204:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
95b0a380b6a8 nginx "/docker-entrypoint.…" 3 seconds ago Up 2 seconds 80/tcp zen_villani
a8626bc92261 nginx "/docker-entrypoint.…" 12 minutes ago Up 12 minutes 0.0.0.0:8888->80/tcp, :::8888->80/tcp web02
48f247f46cab nginx "/docker-entrypoint.…" 16 minutes ago Up 16 minutes 0.0.0.0:80->80/tcp, :::80->80/tcp web01
root@ubuntu2204:~# docker logs zen_villani
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2023/01/04 03:17:17 [notice] 1#1: using the "epoll" event method
2023/01/04 03:17:17 [notice] 1#1: nginx/1.21.5
2023/01/04 03:17:17 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6)
2023/01/04 03:17:17 [notice] 1#1: OS: Linux 5.15.0-43-generic
2023/01/04 03:17:17 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2023/01/04 03:17:17 [notice] 1#1: start worker processes
2023/01/04 03:17:17 [notice] 1#1: start worker process 30
2023/01/04 03:17:17 [notice] 1#1: start worker process 31
root@ubuntu2204:~# docker logs web01
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2023/01/04 03:00:47 [notice] 1#1: using the "epoll" event method
2023/01/04 03:00:47 [notice] 1#1: nginx/1.21.5
2023/01/04 03:00:47 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6)
2023/01/04 03:00:47 [notice] 1#1: OS: Linux 5.15.0-43-generic
2023/01/04 03:00:47 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2023/01/04 03:00:47 [notice] 1#1: start worker processes
2023/01/04 03:00:47 [notice] 1#1: start worker process 31
2023/01/04 03:00:47 [notice] 1#1: start worker process 32
10.0.0.202 - - [04/Jan/2023:03:06:27 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.61.1" "-"
root@ubuntu2204:~#
检索特定时间点之前的日志
root@ubuntu2204:~# docker run --name test -d nginx sh -c "while true; do $(echo date); sleep 1; done"
root@ubuntu2204:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
6613d566a812 nginx "/docker-entrypoint.…" About a minute ago Up About a minute 80/tcp test
95b0a380b6a8 nginx "/docker-entrypoint.…" 4 minutes ago Up 4 minutes 80/tcp zen_villani
a8626bc92261 nginx "/docker-entrypoint.…" 16 minutes ago Up 16 minutes 0.0.0.0:8888->80/tcp, :::8888->80/tcp web02
48f247f46cab nginx "/docker-entrypoint.…" 20 minutes ago Up 20 minutes 0.0.0.0:80->80/tcp, :::80->80/tcp web01
root@ubuntu2204:~# docker logs -f --until=10s test
实际上log就是容器的标准输出
root@ubuntu2204:~# ls /data/docker/
buildkit containers image network overlay2 plugins runtimes swarm tmp trust volumes
root@ubuntu2204:~# ls /data/docker/overlay2/
197a33afbec93f44f15456bd4326d4a5c54ed80dcb525e329eb5e0625651e655 915216af6dab8af27377f95f506182128360db00c4d564b422568c927c288a25-init
274af8f4099d035812b99a2d45652cd4dca273d7db9bb3d9eada764eaefd5b40 966a7329fc06c5e9c59b4b9b419ee06caf17f796342f9a199d0b3ab041aecc3c
36980a6dd0f318d40fa2ceb48b4d27e81833c95ea89f94776c868f32bd1a34a9 9ba8ba2a6fece861e26c40f2c3ab77806f3d9496eccc208a6b6ef19e1af9506d
657928bd618dd8de2b94bc3915f31eb124dde49b36a5f0c568029ec936dadac3 cd11646092115856345f3e4b3380831385a77a54e58930c18e431a90873cf1b7
73cbb9671db1515f18bdf3e274b9cf836ff3b9c925adb438f79da63e1200c056 cd11646092115856345f3e4b3380831385a77a54e58930c18e431a90873cf1b7-init
8ec7c5ca66b2fdb701f0df3b7c1c0ba987e60215d1bf47091c3e7dfc006a7c83 f785ce2b25c54c509bbde9b7d7ae53622bd08443db05fc72b9eb8861fffe3842
8ec7c5ca66b2fdb701f0df3b7c1c0ba987e60215d1bf47091c3e7dfc006a7c83-init f785ce2b25c54c509bbde9b7d7ae53622bd08443db05fc72b9eb8861fffe3842-init
8fef2c8d09ae78da14b279bc1ab1a07de713c530dd8ec53c76c5dd9573c29f11 l
915216af6dab8af27377f95f506182128360db00c4d564b422568c927c288a25
root@ubuntu2204:~# ls /data/docker/overlay2/197a33afbec93f44f15456bd4326d4a5c54ed80dcb525e329eb5e0625651e655/
committed diff link
root@ubuntu2204:~# ls /data/docker/overlay2/915216af6dab8af27377f95f506182128360db00c4d564b422568c927c288a25
diff link lower merged work
root@ubuntu2204:~# ls /data/docker/overlay2/915216af6dab8af27377f95f506182128360db00c4d564b422568c927c288a25/merged/
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@ubuntu2204:~# ls /data/docker/overlay2/915216af6dab8af27377f95f506182128360db00c4d564b422568c927c288a25/merged/var/log/nginx/
access.log error.log
root@ubuntu2204:~# ll /data/docker/overlay2/915216af6dab8af27377f95f506182128360db00c4d564b422568c927c288a25/merged/var/log/nginx/
total 8
drwxr-xr-x 2 root root 4096 Dec 29 2021 ./
drwxr-xr-x 1 root root 4096 Dec 29 2021 ../
lrwxrwxrwx 1 root root 11 Dec 29 2021 access.log -> /dev/stdout #标准输出
lrwxrwxrwx 1 root root 11 Dec 29 2021 error.log -> /dev/stderr
root@ubuntu2204:~#
查看容器无法启动:
docker logs ,但是需要有标准输出才可以
docker inspect
故意端口冲突,让容器起不来。
root@ubuntu2204:~# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
alpine 3.16.2 9c6f07244728 4 months ago 5.54MB
nginx latest 605c77e624dd 12 months ago 141MB
ubuntu jammy 9d28ccdc1fc7 13 months ago 76.3MB
root@ubuntu2204:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
6613d566a812 nginx "/docker-entrypoint.…" 17 minutes ago Up 17 minutes 80/tcp test
95b0a380b6a8 nginx "/docker-entrypoint.…" 20 minutes ago Up 20 minutes 80/tcp zen_villani
a8626bc92261 nginx "/docker-entrypoint.…" 32 minutes ago Up 32 minutes 0.0.0.0:8888->80/tcp, :::8888->80/tcp web02
48f247f46cab nginx "/docker-entrypoint.…" 36 minutes ago Up 36 minutes 0.0.0.0:80->80/tcp, :::80->80/tcp web01
root@ubuntu2204:~# docker run -d -p 8888:80 --name web03 nginx #启动的时候有错误提示信息
38409cb7a807828b636ecb0461e7e8d3dae026292ac6fe112c04f0fecd074136
docker: Error response from daemon: driver failed programming external connectivity on endpoint web03 (81f9adb36fa5adad5442b4e4f1e0dd45c629bca08ef7cac4ac1b5e3f73303289): Bind for 0.0.0.0:8888 failed: port is already allocated.
root@ubuntu2204:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
38409cb7a807 nginx "/docker-entrypoint.…" 9 seconds ago Created web03
6613d566a812 nginx "/docker-entrypoint.…" 17 minutes ago Up 17 minutes 80/tcp test
95b0a380b6a8 nginx "/docker-entrypoint.…" 20 minutes ago Up 20 minutes 80/tcp zen_villani
a8626bc92261 nginx "/docker-entrypoint.…" 33 minutes ago Up 32 minutes 0.0.0.0:8888->80/tcp, :::8888->80/tcp web02
48f247f46cab nginx "/docker-entrypoint.…" 37 minutes ago Up 37 minutes 0.0.0.0:80->80/tcp, :::80->80/tcp web01
root@ubuntu2204:~# docker logs web03 #此时日志没有输出
root@ubuntu2204:~# docker inspect web03 |grep -i -C 10 ERROR #容器详细信息里面提示有错误信息
],
"State": {
"Status": "created",
"Running": false,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 0,
"ExitCode": 128,
"Error": "driver failed programming external connectivity on endpoint web03 (81f9adb36fa5adad5442b4e4f1e0dd45c629bca08ef7cac4ac1b5e3f73303289): Bind for 0.0.0.0:8888 failed: port is already allocated",
"StartedAt": "0001-01-01T00:00:00Z",
"FinishedAt": "0001-01-01T00:00:00Z"
},
"Image": "sha256:605c77e624ddb75e6110f997c58876baa13f8754486b461117934b24a9dc3a85",
"ResolvConfPath": "/data/docker/containers/38409cb7a807828b636ecb0461e7e8d3dae026292ac6fe112c04f0fecd074136/resolv.conf",
"HostnamePath": "",
"HostsPath": "/data/docker/containers/38409cb7a807828b636ecb0461e7e8d3dae026292ac6fe112c04f0fecd074136/hosts",
"LogPath": "/data/docker/containers/38409cb7a807828b636ecb0461e7e8d3dae026292ac6fe112c04f0fecd074136/38409cb7a807828b636ecb0461e7e8d3dae026292ac6fe112c04f0fecd074136-json.log",
"Name": "/web03",
"RestartCount": 0,
root@ubuntu2204:~#
2.11 容器内部hosts文件
容器会自动将容器的ID加入自已的/etc/hosts文件中,并解析成容器的IP
容器ID与容器IP映射
root@ubuntu2204:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
81e0f8898097 alpine:3.16.2 "tail -f /etc/hosts" 7 minutes ago Up 7 minutes eager_lalande
root@ubuntu2204:~# docker exec eager_lalande bash
OCI runtime exec failed: exec failed: unable to start container process: exec: "bash": executable file not found in $PATH: unknown
root@ubuntu2204:~# docker exec -it eager_lalande 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.2 81e0f8898097 #容器ID与容器IP映射
/ #hostname
81e0f8898097
/ # ping 81e0f8898097 #ping容器ID能够ping通
PING 81e0f8898097 (172.17.0.2): 56 data bytes
64 bytes from 172.17.0.2: seq=0 ttl=64 time=0.049 ms
64 bytes from 172.17.0.2: seq=1 ttl=64 time=0.037 ms
64 bytes from 172.17.0.2: seq=2 ttl=64 time=0.038 ms
64 bytes from 172.17.0.2: seq=3 ttl=64 time=0.117 ms
^C
--- 81e0f8898097 ping statistics ---
4 packets transmitted, 4 packets received, 0% packet loss
round-trip min/avg/max = 0.037/0.060/0.117 ms
/ # eixt
sh: eixt: not found
/ # exit
root@ubuntu2204:~#
root@ubuntu2204:~# docker run --add-host=docker:93.184.216.34 --rm -it alpine
/ # ping docker
PING docker (93.184.216.34): 56 data bytes
64 bytes from 93.184.216.34: seq=0 ttl=37 time=93.052 ms
64 bytes from 93.184.216.34: seq=1 ttl=37 time=92.467 ms
64 bytes from 93.184.216.34: seq=2 ttl=37 time=92.252 ms
^C
--- docker ping statistics ---
4 packets transmitted, 4 packets received, 0% packet loss
round-trip min/avg/max = 92.209/92.495/93.052 ms
/ # 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
93.184.216.34 docker
172.17.0.3 18cad3231067
/ # exit
bash: /: Is a directory
bash: syntax error near unexpected token `('
64: command not found
64: command not found
64: command not found
bash: :s^C: substitution failed
---: command not found
4: command not found
round-trip: command not found
root@ubuntu2204:~#
2.12 容器和本地文件系统之间复制文件/文件夹
docker cp
在容器和本地文件系统之间复制文件/文件夹
root@ubuntu2204:~# 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.
Options:
-a, --archive Archive mode (copy all uid/gid information)
-L, --follow-link Always follow symbol link in SRC_PATH
#选项
--archive,-a 存档模式(复制所有 uid/gid 信息)
--follow-link,-L 始终遵循SRC_PATH中的符号链接
2.13 systemd 控制容器运行
root@ubuntu2204:~# vim /etc/docker/daemon.json
{
"data-root":"/data/docker/", #指定docker根目录
"registry-mirrors": ["https://uietgfqt.mirror.aliyuncs.com"], #镜像加速器
"live-restore": true #关闭容器服务而不关闭,默认flase容器关闭服务就关闭
}
root@ubuntu2204:~# systemctl daemon-reload
root@ubuntu2204:~# systemctl restart docker
2.14 容器重启
docker restart
重新启动一个或多个容器
root@ubuntu2204:~# docker restart --help
Usage: docker restart [OPTIONS] CONTAINER [CONTAINER...]
Restart one or more containers
Options:
-t, --time int Seconds to wait for stop before killing the container (default 10)
#选项
--time,-t 10 在杀死容器之前等待停止的秒数
docker run --restart
Restart policy to apply when a container exits (default “no”)
policy 说明 ,–restart 可以指定四种不同的policy
2.15 显示容器资源使用情况
docker stats
显示容器资源使用情况统计信息的实时流
root@ubuntu2204:~# docker stats --help
Usage: 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
#选项
--all,-a 显示所有容器(默认显示刚刚运行)
--format 使用 Go 模板打印漂亮的图像
--no-stream 禁用流统计信息并仅提取第一个结果
--no-trunc 不截断输出
示例:
root@ubuntu2204:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
04e5f5f9ee9f mysql:5.7.32 "docker-entrypoint.s…" 42 minutes ago Up 42 minutes 0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp mysql-test1
root@ubuntu2204:~# docker stats mysql-test1
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
04e5f5f9ee9f mysql-test1 0.05% 194.2MiB / 3.8GiB 4.99% 1.37kB / 0B 0B / 583MB 27
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
04e5f5f9ee9f mysql-test1 0.05% 194.2MiB / 3.8GiB 4.99% 1.37kB / 0B 0B / 583MB 27
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
04e5f5f9ee9f mysql-test1 0.07% 194.2MiB / 3.8GiB 4.99% 1.37kB / 0B 0B / 583MB 27
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
04e5f5f9ee9f mysql-test1 0.07% 194.2MiB / 3.8GiB 4.99% 1.37kB / 0B 0B / 583MB 27
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
04e5f5f9ee9f mysql-test1 0.04% 194.2MiB / 3.8GiB 4.99% 1.37kB / 0B 0B / 583MB 27
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
04e5f5f9ee9f mysql-test1 0.04% 194.2MiB / 3.8GiB 4.99% 1.37kB / 0B 0B / 583MB 27
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
04e5f5f9ee9f mysql-test1 0.08% 194.2MiB / 3.8GiB 4.99% 1.37kB / 0B 0B / 583MB 27
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
04e5f5f9ee9f mysql-test1 0.08% 194.2MiB / 3.8GiB 4.99% 1.37kB / 0B 0B / 583MB 27
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
04e5f5f9ee9f mysql-test1 0.10% 194.2MiB / 3.8GiB 4.99% 1.37kB / 0B 0B / 583MB 27
^C
root@ubuntu2204:~#
2.16 显示正在运行容器的进程ID
docker top
docker container top CONTAINER [ps OPTIONS]
root@ubuntu2204:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
04e5f5f9ee9f mysql:5.7.32 "docker-entrypoint.s…" 52 minutes ago Up 52 minutes 0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp mysql-test1
root@ubuntu2204:~# docker top mysql-test1
UID PID PPID C STIME TTY TIME CMD
lxd 12349 12328 0 05:43 ? 00:00:02 mysqld
root@ubuntu2204:~#