将静态IP分配给Docker容器 [英] Assign static IP to Docker container
问题描述
当Docker容器启动时,我正在尝试分配静态IP 172.17.0.1。
I'm now trying to assign a static IP 172.17.0.1 when a Docker container be started up.
我使用端口2122作为此容器的ssh端口,以便我让此容器侦听端口2122。
I use port 2122 as the ssh port of this container so that I let this container listen port 2122.
sudo docker run -i -t -p 2122:2122 ubuntu
此命令将运行带有随机IP的Docker容器,如172.17.0.5,但是我需要为容器分配一个特定的IP。
This command will run a Docker container with a random IP like 172.17.0.5, but I need to assign a specific IP to the container.
以下shell脚本是我在高级网络设置中引用了Docker文档。
The following shell script is what I reference Docker documentation in advanced network settings.
pid=$(sudo docker inspect -f '{{.State.Pid}}' <container_name> 2>/dev/null)
sudo rm -rf /var/run/netns/*
sudo ln -s /proc/$pid/ns/net /var/run/netns/$pid
sudo ip link add A type veth peer name B
sudo brctl addif docker0 A
sudo ip link set A up
sudo ip link set B netns $pid
sudo ip netns exec $pid ip link set eth0 down
sudo ip netns exec $pid ip link delete eth0
sudo ip netns exec $pid ip link set dev B name eth0
sudo ip netns exec $pid ip link set eth0 address 12:34:56:78:9a:bc
sudo ip netns exec $pid ip link set eth0 down
sudo ip netns exec $pid ip link set eth0 up
sudo ip netns exec $pid ip addr add 172.17.0.1/16 dev eth0
sudo ip netns exec $pid ip route add default via 172.17.42.1
此shell脚本将分配静态IP 172.17.0.1并链接到世界各地。但是每当我尝试从我的本地ssh到这个容器,它没有工作。可能遇到的问题是什么?
This shell script will assign a static IP 172.17.0.1 and link to the world fine. But whenever I try to ssh to this container from my local, it didn't work. What's the problem possibly I met?
推荐答案
容易与Docker版本1.10.1,构建9e83765。
Easy with Docker version 1.10.1, build 9e83765.
首先您需要创建自己的码头网络(mynet123)
First you need to create you own docker network (mynet123)
docker network create --subnet=172.18.0.0/16 mynet123
不仅仅是运行图像(我以ubuntu为例)
than simply run the image (I'll take ubuntu as example)
docker run --net mynet123 --ip 172.18.0.22 -it ubuntu bash
然后在ubuntu shell
then in ubuntu shell
ip addr
此外,您可以使用
-
- 主机名
指定主机名 -
- 添加主机
添加更多条目到/ etc / hosts
--hostname
to specify a hostname--add-host
to add more entries to /etc/hosts
文档(以及为什么需要创建一个网络)在 https://docs.docker.com/engine/reference/commandline/net work_create /
Docs (and why you need to create a network) at https://docs.docker.com/engine/reference/commandline/network_create/
这篇关于将静态IP分配给Docker容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!