How docker generates container's names

docker names

2 min read | by Jordi Prats

Everytime you create a container using docker, if not already set using --name, docker chooses a name for you: you can expect two words with a underscore:

$ docker run --rm -d alpine sleep 24h
38c4cc4e87762fc113ef174e9a4989e13d21037678abd3fe73840b825f14c7bf
$ docker ps
CONTAINER ID   IMAGE                          COMMAND                  CREATED         STATUS                PORTS                    NAMES
38c4cc4e8776   alpine                         "sleep 24h"              5 seconds ago   Up 3 seconds                                   romantic_shtern

For this example it was chosen romantic_shtern, but it can use a great variety of words:

$ docker ps --all | grep -v "Up" | awk '{ print $NF }'
NAMES
mystifying_poitras
suspicious_shtern
focused_chatelet
keen_mendel
happy_jackson
xenodochial_margulis
kind_blackburn
gallant_pascal
trusting_thompson
(...)

So, how does Docker generate names for it's containers?

If we take a look at the moby/moby repository (that's where docker development takes place) we'll find the namesgenerator package (/pkg/namesgenerator/)

In it we can see how it uses two list, one each word: For the left hand one it's just a list of adjectives, but for the right one it is a list of names from notable scientists and hackers (starting from 0.7.x)

This package also contains the function that generates the name, since it needs to be unique, it can append a random number if it found a collision:

  if retry > 0 {
    name += strconv.Itoa(rand.Intn(10)) //nolint:gosec // G404: Use of weak random number generator (math/rand instead of crypto/rand)
  }

But the more interesting bit is how it has one exception for Steve Wozniak:

func GetRandomName(retry int) string {
begin:
  name := left[rand.Intn(len(left))] + "_" + right[rand.Intn(len(right))] //nolint:gosec // G404: Use of weak random number generator (math/rand instead of crypto/rand)
  if name == "boring_wozniak" /* Steve Wozniak is not boring */ {
    goto begin
  }

  if retry > 0 {
    name += strconv.Itoa(rand.Intn(10)) //nolint:gosec // G404: Use of weak random number generator (math/rand instead of crypto/rand)
  }
  return name
}

So, if the generated name turns out to be boring_wozniak, it just picks another one. You can see it by yourself on github(moby/moby) /pkg/namesgenerator/names-generator.go


Posted on 01/08/2022

Categories