How to set docker container hostname/IP permanently?
You can use docker-compose
tool to create a stack of containers with specific hostnames and addresses.
Here is the example docker-compose.yml
with specific network config:
version: "2"
services:
host1:
networks:
mynet:
ipv4_address: 172.25.0.101
networks:
mynet:
driver: bridge
ipam:
config:
- subnet: 172.25.0.0/24
Source: Docker Compose static IP address in docker-compose.yml
.
And here is the example of docker-compose.yml
file with containers pinging each other:
version: '3'
services:
ubuntu01:
image: bash
hostname: ubuntu01
command: ping -c1 ubuntu02
ubuntu02:
image: bash
hostname: ubuntu02
command: ping -c1 ubuntu01
Run with docker-compose up
.
You can use the new networking feature available after Docker version 1.10.0
That allows you to connect to containers by their name, assign Ip addrees and host names.
When you create a new network, any container connected to that network can reach other containers by their name, ip or host-names.
i.e:
1) Create network
$ docker network create --subnet=172.18.0.0/16 mynet123
2) Create container inside the network
$ docker run --net mynet123 -h myhostname --ip 172.18.0.22 -it ubuntu bash
Flags:
--net
connect a container to a network--ip
to specify IPv4 address-h, --hostname
to specify a hostname--add-host
to add more entries to /etc/hosts