Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set docker container hostname/IP permanently?

Tags:

docker

Is there a way to permanently set a hostname and IP to a container in docker? I want to create a stack of machines (containers) in one VM ideally talking to one another with hostname.

like image 909
san1512 Avatar asked Feb 17 '16 19:02

san1512


2 Answers

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
like image 139
Hemerson Varela Avatar answered Nov 17 '22 05:11

Hemerson Varela


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.

like image 7
kenorb Avatar answered Nov 17 '22 05:11

kenorb