列出docker镜像

1
docker images -a

列出docker网络

1
docker network ls

列出所有容器基本信息

1
docker ps -a

运行容器并进入容器内部

1
2
3
4
docker run -it -P --network localnet -v /var/www/html:/var/www/html fauria/lamp:v2  /bin/bash
# -P 将容器内服务端口随机映射到主机端口
# --network 将容器网络连接到指定网络,例如Host、bridge
# -v 将主机的目录映射到容器内的某个目录

退出容器并保持容器后台运行

1
键盘按键组合:  Ctrl+p+q

查看指定容器端口映射

1
docker port	container_id

进入到正在运行的容器内部

1
docker exec -it 0 /bin/bash

查看某个容器的详细配置

1
docker inspect container_name 

查看某个容器的PID

1
docker inspect trusting_mayer -f '{{.State.Pid}}'

查看某个网络的具体配置

1
docker network inspect bridge # 查看bridge网络

查看容器的ns

问题及解决: docker创建的Network Namespace无法显示

问题

Docker Container Network Namespace is Invisible

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 查看container PID
$ docker inspect container_name -f '{{.State.Pid}}'
# 在 /proc/{pid}/ns 查看对应container进程的 NameSpace
$ ls -al /proc/3180/ns
total 0
dr-x--x--x 2 root root 0 Apr 21 20:03 .
dr-xr-xr-x 9 root root 0 Apr 21 20:03 ..
lrwxrwxrwx 1 root root 0 Apr 21 20:13 cgroup -> 'cgroup:[4026531835]'
lrwxrwxrwx 1 root root 0 Apr 21 20:04 ipc -> 'ipc:[4026532637]'
lrwxrwxrwx 1 root root 0 Apr 21 20:04 mnt -> 'mnt:[4026532635]'
lrwxrwxrwx 1 root root 0 Apr 21 20:03 net -> 'net:[4026532640]'
lrwxrwxrwx 1 root root 0 Apr 21 20:04 pid -> 'pid:[4026532638]'
lrwxrwxrwx 1 root root 0 Apr 21 20:13 pid_for_children -> 'pid:[4026532638]'
lrwxrwxrwx 1 root root 0 Apr 21 20:13 time -> 'time:[4026531834]'
lrwxrwxrwx 1 root root 0 Apr 21 20:13 time_for_children -> 'time:[4026531834]'
lrwxrwxrwx 1 root root 0 Apr 21 20:13 user -> 'user:[4026531837]'
lrwxrwxrwx 1 root root 0 Apr 21 20:04 uts -> 'uts:[4026532636]'

从namespace目录伪文件列表中,我们可以看到此过程的net文件的存在。由于Net文件对应于Linux网络命名空间,因此我们可以在列出所有网络名称空间时显示它。但是,我们可以看到并非如此。例如,运行ip netns ls显示无结果:

1
2
$ ip netns ls
$

作为对比,我们手动创建的ns是可以列出的:

1
2
3
$ ip netns add own_netns1
$ ip netns ls
own_netns1

原因

ip netns ls是在/var/run/netns目录下寻找netns的,但是docker并不会在这个目录下创建ns的引用文件,所以netns命令无法找到docker创建的netns。

docker的容器所在的网络空间可以通过inspect查看

image-20220422122134027

解决办法

  1. /var/run/netns目录下创建个以容器id命名的空文件

    1
    2
    $ mkdir -p /var/run/netns
    $ touch /var/run/netns/$container_id
  2. /proc/{PID}/ns/net 或者/var/run/docker/netns/{id}文件挂载到/var/run/netns/$container_id

    1
    mount -o bind /var/run/docker/netns/86e269290fda /var/run/netns/86e269290fda

    image-20220422125137065

    注意不要用软连接来代替mount,因为pid是可重用的,可能会造成docker结束后ip netns错误寻找成其他进程netns。

阿斯顿


Docker-从入门到实践

研究pipework