2016年5月31日 星期二

[ 常見問題 ] How can I set a static IP address in a Docker container?

Source From Here 
Question 
I'm perfectly happy with the IP range that docker is giving me by default (176.17.x.x), so I don't need to create a new bridge, I just want to give my containers a static address within that range so I can point client browsers to it directly. 

How-To 
I used the method written here in the official Docker documentation and I confirm it's working: 
# docker images
# d run -it --rm --net=none johnklee/hadoop_centos_base:v1 /bin/bash // Run container on image johnklee/hadoop_centos_base:v1

// At another shell, learn the container process ID
// and create its namespace entry in /var/run/netns/
// for the "ip netns" command we will be using below

# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
6f072051949b johnklee/hadoop_centos_base:v1 "/bin/bash" About a minute ago Up About a minute prickly_lumiere
 // Container ID = 6f072051949b
# d inspect -f '{{.State.Pid}}' 6f072051949b
73172
# mkdir -p /var/run/netns
# ln -sf /proc/73172/ns/net /var/run/netns/73172

// Check the bridge's IP address and netmask
# ip addr show docker0
3: docker0: mtu 1500 qdisc noqueue state DOWN
link/ether 02:42:ff:5d:2b:07 brd ff:ff:ff:ff:ff:ff
inet 172.17.42.1/16 scope global docker0
...


// Create a pair of "peer" interfaces A and B,
// bind the A end to the bridge, and bring it up

# ip link add A type veth peer name B
# brctl addif docker0 A
# ip link set A up

// Place B inside the container's network namespace,
// rename to eth0, and activate it with a free IP

# ip link set B netns 73172
# ip netns exec 73172 ip link set dev B name eth0
# ip netns exec 73172 ip link set eth0 up
# ip netns exec 73172 ip addr add 172.17.42.100/16 dev eth0
# ip netns exec 73172 ip route add default via 172.17.42.1

// Back to docker container terminal to confirm the setting is working
[root@6f072051949b /]# ip addr show
...
134: eth0: mtu 1500 qdisc pfifo_fast state UP qlen 1000
link/ether 16:83:8b:a3:49:58 brd ff:ff:ff:ff:ff:ff
inet 172.17.42.100/16 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::1483:8bff:fea3:4958/64 scope link
valid_lft forever preferred_lft forever

[root@6f072051949b /]# ping -c 3 www.google.com.tw
PING www.google.com.tw (74.125.203.94) 56(84) bytes of data.
64 bytes from th-in-f94.1e100.net (74.125.203.94): icmp_seq=1 ttl=127 time=123 ms
64 bytes from th-in-f94.1e100.net (74.125.203.94): icmp_seq=2 ttl=127 time=89.0 ms
...
 


Supplement 
[ 常見問題 ] Add link between container and bridge

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...