zer*_*iel 36 linux lxc namespace
Linux 中是否有任何方法可以列出正在运行的主机上的所有命名空间?我需要检查特定进程的命名空间(例如,在 LXC 容器中运行的进程和主机上的所有其他进程),然后找出它们的 cgroup。
cas*_*cas 31
自从 2013 年提出这个问题以来,使用命名空间的实用程序得到了改进。
lsns从util-linux包中可以列出所有不同类型的命名空间,以各种有用的格式。
# lsns --help
Usage:
lsns [options] [<namespace>]
List system namespaces.
Options:
-J, --json use JSON output format
-l, --list use list format output
-n, --noheadings don't print headings
-o, --output <list> define which output columns to use
-p, --task <pid> print process namespaces
-r, --raw use the raw output format
-u, --notruncate don't truncate text in columns
-t, --type <name> namespace type (mnt, net, ipc, user, pid, uts, cgroup)
-h, --help display this help and exit
-V, --version output version information and exit
Available columns (for --output):
NS namespace identifier (inode number)
TYPE kind of namespace
PATH path to the namespace
NPROCS number of processes in the namespace
PID lowest PID in the namespace
PPID PPID of the PID
COMMAND command line of the PID
UID UID of the PID
USER username of the PID
For more details see lsns(8).
Run Code Online (Sandbox Code Playgroud)
lsns只列出每个进程的最低 PID - 但pgrep如果你想列出属于命名空间的所有进程,你可以使用该 PID 。
例如,如果我在 docker 中运行 gitlab 并且想要找到在该命名空间中运行的所有进程,我可以:
# lsns -t pid -o ns,pid,command | grep gitlab
4026532661 459 /opt/gitlab/embedded/bin/redis-server 127.0.0.1:0
Run Code Online (Sandbox Code Playgroud)
然后,使用该 pid (459) 与pgrep:
# pgrep --ns 459 -a
459 /opt/gitlab/embedded/bin/redis-server 127.0.0.1:0
623 postgres: gitlab gitlabhq_production [local] idle
[...around 50 lines deleted...]
30172 nginx: worker process
Run Code Online (Sandbox Code Playgroud)
我还可以将命名空间 id (4026532661) 与 一起使用ps,例如:
ps -o pidns,pid,cmd | awk '$1==4026532661'
[...output deleted...]
Run Code Online (Sandbox Code Playgroud)
来自网络名称空间的 ip 手册页
ip netns - 进程网络命名空间管理 网络命名空间在逻辑上是网络堆栈的另一个副本,具有自己的路由、防火墙规则和网络设备。
By convention a named network namespace is an object at
/var/run/netns/NAME that can be opened. The file descriptor resulting
from opening /var/run/netns/NAME refers to the specified network names-
pace. Holding that file descriptor open keeps the network namespace
alive. The file descriptor can be used with the setns(2) system call
to change the network namespace associated with a task.
The convention for network namespace aware applications is to look for
global network configuration files first in /etc/netns/NAME/ then in
/etc/. For example, if you want a different version of
/etc/resolv.conf for a network namespace used to isolate your vpn you
would name it /etc/netns/myvpn/resolv.conf.
Run Code Online (Sandbox Code Playgroud)
对于其他类型的名称空间,也许还有其他方法