root@ubuntu:/home/ubuntu# docker run -itd --name test ubuntu /bin/bash 86d1bf0df1c9ff0a705be14b5263473f5c2d2bbbcc01b7159494047d74a51647 root@ubuntu:/home/ubuntu# docker ps | grep 86d1bf0df1c9 86d1bf0df1c9 ubuntu "/bin/bash" 19 seconds ago Up 18 seconds test root@ubuntu:/home/ubuntu# docker inspect --format '{{ .State.Pid }}' test 58831
#define _GNU_SOURCE #include <fcntl.h> #include <sched.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); } while (0) int main(int argc, char *argv[]) { int fd; if (argc < 3) { fprintf(stderr, "%s /proc/PID/ns/FILE cmd args... ", argv[0]); exit(EXIT_FAILURE); } fd = open(argv[1], O_RDONLY); // Get descriptor for namespace if (fd == -1) errExit("open"); if (setns(fd, 0) == -1) // Join that namespace errExit("setns"); execvp(argv[2], &argv[2]); // Execute a command in namspace errExit("execvp"); }
root@ubuntu:/home/ubuntu/test# ./ns /proc/58831/ns/net /bin/bash root@ubuntu:/home/ubuntu/test# 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 386: eth0@if387: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default link/ether 02:42:ac:11:00:04 brd ff:ff:ff:ff:ff:ff link-netnsid 0 inet 172.17.0.4/16 brd 172.17.255.255 scope global eth0 valid_lft forever preferred_lft forever root@ubuntu:/home/ubuntu/test#
root@ubuntu:/home/ubuntu/test# ls -l /proc/58831/ns/net lrwxrwxrwx 1 root root 0 Nov 24 15:54 /proc/58831/ns/net -> 'net:[4026534375]' root@ubuntu:/home/ubuntu/test# ls -l /proc/59899/ns/net lrwxrwxrwx 1 root root 0 Nov 24 16:03 /proc/59899/ns/net -> 'net:[4026534375]' root@ubuntu:/home/ubuntu/test# 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 386: eth0@if387: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default link/ether 02:42:ac:11:00:04 brd ff:ff:ff:ff:ff:ff link-netnsid 0 inet 172.17.0.4/16 brd 172.17.255.255 scope global eth0 valid_lft forever preferred_lft forever root@ubuntu:/home/ubuntu/test#