玩转linux network namespace

2017-12-21  本文已影响0人  2099_3c91

使用ip netns操作network namespace

创建一个network namespace

  1. 创建一个network namespace
ip netns add nstest
ip netns list 
  1. 删除一个network namespace
ip netns delete nstest 
ip netns list 

3.在network namespace 中执行一条命令,如显示nstest中的网卡信息

ip netns exec nstest ip addr 

或直接打开一个Bash,在里面执行命令,用exit退出

ip netns exec nstest bash

配置network namespace

  1. 配置网卡
    启动默认添加的网络回环设备,回环设备默认是关闭的
ip netns exec nstest ip link set dev lo up

在主机上添加两块虚拟网卡veth-a和veth-b

ip link add veth-a type  veth peer name veth-b
ip addr 

将veth-b加入到nstest这个network namespace中,veth-a留在主机中

ip link set veth-b netns nstest
ip netns exec nstest ip link

为网卡分配IP地址

#为主机的veth-a分配ip
ip addr add 10.0.0.1/24 dev veth-a
ip link set dev veth-a up
# 为nstest中的veth-b配置ip并启动
ip netns exec nstest ip addr add 10.0.0.2/24 dev veth-b
ip netns exec nstest ip link set dev veth-b up
#验证连通性
[root@cyt-aliyun-test ~]# ping 10.0.0.2 
PING 10.0.0.2 (10.0.0.2) 56(84) bytes of data.
64 bytes from 10.0.0.2: icmp_seq=1 ttl=64 time=0.065 ms
[root@cyt-aliyun-test ~]# ip netns exec nstest ping 10.0.0.1 
PING 10.0.0.1 (10.0.0.1) 56(84) bytes of data.
64 bytes from 10.0.0.1: icmp_seq=1 ttl=64 time=0.048 ms
64 bytes from 10.0.0.1: icmp_seq=2 ttl=64 time=0.054 ms
64 bytes from 10.0.0.1: icmp_seq=3 ttl=64 time=0.060 ms

使用ip命令配置docker容器网络

# 查看容器的pid
[root@cyt-aliyun-test ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                  NAMES
354e7442c0b1        php-apache:5.6.31   "docker-php-entrypoin"   6 weeks ago         Up 6 weeks          0.0.0.0:8080->80/tcp   kod
[root@cyt-aliyun-test ~]# docker inspect --format '{{.State.Pid}}' kod
16289
#若不存在/var/run/netns目录,则创建目录
mkdir -p /var/run/netns
#在/var/run/netns/目录下创建软链接,指向kod容器的network namespace
[root@cyt-aliyun-test netns]# ln -s /proc/16289/ns/net /var/run/netns/kod
#测试
[root@cyt-aliyun-test netns]# ip netns exec kod ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN qlen 1
    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
34: eth0@if35: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP 
    link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 172.17.0.2/16 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::42:acff:fe11:2/64 scope link 
       valid_lft forever preferred_lft forever
[root@cyt-aliyun-test netns]# ip netns list
kod (id: 1)
nstest (id: 0)





















上一篇下一篇

猜你喜欢

热点阅读