问题描述
我现在尝试在 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.
首先,您需要创建自己的 docker 网络 (mynet123)
First you need to create your own docker network (mynet123)
docker network create --subnet=172.18.0.0/16 mynet123
然后,只需运行图像(我将以 ubuntu 为例)
then, 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 添加更多条目
--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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!