在使用docker的时候如果我们不使用—-name 参数指定容器名称,docker会随机生成一个容器名称,例如:

ryan@ubuntu:~$ sudo docker run hello-world
ryan@ubuntu:~$ sudo docker container ls -a --format "table {{.ID}}\t{{.Names}}\t{{.Status}}"
CONTAINER ID   NAMES                 STATUS
f394aae27522   busy_fermat           Exited (0) 3 seconds ago

这个随机名称是怎么来的呢?如果看一下moby/moby 这个仓库就会发现端倪,在pkg/namegenerator目录下面有个namegenerator.go这个文件。

namegenerator.go里面有个两个单词组,分为left和right两组,left的单词组为一些形容词,right的单词组为一些著名计算机科学家或者黑客:

left = [...]string{
		"admiring",
		"adoring",
		"affectionate",
		"agitated",
		"amazing",
		"angry",
		"awesome",
		"beautiful",
		"blissful",
		"bold",
		"boring",
		"brave",
		"busy",
		"charming",
		
		......
right = [...]string{
		// Maria Gaetana Agnesi - Italian mathematician, philosopher, theologian and humanitarian. She was the first woman to write a mathematics handbook and the first woman appointed as a Mathematics Professor at a University. https://en.wikipedia.org/wiki/Maria_Gaetana_Agnesi
		"agnesi",

		// Muhammad ibn Jābir al-Ḥarrānī al-Battānī was a founding father of astronomy. https://en.wikipedia.org/wiki/Mu%E1%B8%A5ammad_ibn_J%C4%81bir_al-%E1%B8%A4arr%C4%81n%C4%AB_al-Batt%C4%81n%C4%AB
		"albattani",

		// Frances E. Allen, became the first female IBM Fellow in 1989. In 2006, she became the first female recipient of the ACM's Turing Award. https://en.wikipedia.org/wiki/Frances_E._Allen
		"allen",

		// June Almeida - Scottish virologist who took the first pictures of the rubella virus - https://en.wikipedia.org/wiki/June_Almeida
		"almeida",

		// Kathleen Antonelli, American computer programmer and one of the six original programmers of the ENIAC - https://en.wikipedia.org/wiki/Kathleen_Antonelli
		"antonelli",

		// Archimedes was a physicist, engineer and mathematician who invented too many things to list them here. https://en.wikipedia.org/wiki/Archimedes
		"archimedes",

		// Maria Ardinghelli - Italian translator, mathematician and physicist - https://en.wikipedia.org/wiki/Maria_Ardinghelli
		"ardinghelli",
	
		......

通过left和right两组单词随机组合生成容器名称。如果随机生成的名称有碰撞则在名字后面添加随机数:

if retry > 0 {
		name += strconv.Itoa(rand.Intn(10)) //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
	}

如果随机生成的名字是boring_wozniak,那么重新生成一个随机名字,哈哈 😀