Linux – How to get all IP addresses mapped to a specific hostname of a docker container in bash

How to get all IP addresses mapped to a specific hostname of a docker container in bash… here is a solution to the problem.

How to get all IP addresses mapped to a specific hostname of a docker container in bash

I’m scaling multiple Redis containers with Docker compose and want to find a way to get all the IP addresses that correspond to a specific hostname in bash. I have 5 Redis containers and they all have the hostname redis. I tried the command getent hosts redis | awk '{ print $1 }' hoping to get all the IP addresses of the redis Docker image, but each time it only returns one of them. Here’s sample output from running the command a few times without using awk in one of the Redis containers:

bash-4.4# getent hosts redis
172.16.0.7        redis  redis
bash-4.4# getent hosts redis
172.16.0.6        redis  redis
bash-4.4# getent hosts redis
172.16.0.5        redis  redis
bash-4.4# getent hosts redis
172.16.0.6        redis  redis

I want a way to get all IP addresses in one command. Does anyone know how to do this in bash?

EDIT: My question is different because instead of getting the IP address of the host, I want to get all the IP addresses that match the hostname by running bash I script myself in the container.

Solution

I was able to do this using dig redis A | grep redis inside the container. In addition to some additional information, it outputs all IP addresses, so now I can parse them from the output and add them to the bash array.

Related Problems and Solutions