Docker Compose主机名命令不起作用

我无法使Docker Compose hostname命令正常工作。

我正在运行一个简单docker-compose.yml

 version: '3' services: redis1: image: "redis:alpine" hostname: redis1host redis2: image: "redis:alpine" hostname: redis2host 

一旦我用docker-compose up运行这个,我应该可以运行docker-compose exec redis1 /bin/ash ,然后ping redis2host与另一个Redis容器进行通信,但ping只是没有到达目的地。 我可以用ping redis2来ping另一个Redis容器。

ping redishost2应该可以,不是吗?

hostname指令简单地设置容器内的主机名(也就是你响应hostnameuname -n命令返回的名称)。 它不会导致该服务的DNS别名。 为此,您需要别名指令。 由于该指令是按networking进行的,因此您需要明确networking而不是使用组合默认值,例如:

 version: '3' services: redis1: image: "redis:alpine" hostname: redis1host networks: redis: aliases: - redis1host redis2: image: "redis:alpine" hostname: redis2host networks: redis: aliases: - redis2host networks: redis: