如何在 Docker 容器中设置静态 IP 地址? [英] How can I set a static IP address in a Docker container?
问题描述
我对 docker 默认给我的 IP 范围非常满意 176.17.xx
,所以我不需要创建新的网桥,我只想给我的容器一个在该范围内的静态地址,以便我可以将客户端浏览器直接指向它.我尝试使用
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.
I tried using
RUN echo "auto eth0" >> /etc/network/interfaces
RUN echo "iface eth0 inet static" >> /etc/network/interfaces
RUN echo "address 176.17.0.250" >> /etc/network/interfaces
RUN echo "netmask 255.255.0.0" >> /etc/network/interfaces
RUN ifdown eth0
RUN ifup eth0
来自 Dockerfile,它正确填充了接口文件,但接口本身没有改变.事实上,在容器内运行 ifup eth0 会得到这个错误:
from a Dockerfile, and it properly populated the interfaces file, but the interface itself didn't change. In fact, running ifup eth0 within the container gets this error:
RTNETLINK 回答:不允许操作无法启动 eth0
RTNETLINK answers: Operation not permitted Failed to bring up eth0
推荐答案
我已经在这里回答了https://stackoverflow.com/a/35359185/4094678但我现在看到这个问题实际上比前面提到的问题更老,所以我也会复制答案:
I have already answered this here https://stackoverflow.com/a/35359185/4094678 but I see now that this question is actually older then the aforementioned one, so I'll copy the answer as well:
使用 Docker 版本 1.10.1 轻松构建 9e83765.
Easy with Docker version 1.10.1, build 9e83765.
首先你需要创建你自己的docker网络(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
另外你可以使用--hostname
指定主机名--add-host
将更多条目添加到 /etc/hosts
Additionally you could use
--hostname
to specify a hostname
--add-host
to add more entries to /etc/hosts
文档(以及为什么需要创建网络)位于 https://docs.docker.com/engine/reference/commandline/network_create/
Docs (and why you need to create a network) at https://docs.docker.com/engine/reference/commandline/network_create/
这篇关于如何在 Docker 容器中设置静态 IP 地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!