how to return "localhost" from InetAddress.getLocalHost().getHostName() in docker container

Viewed 2408

In my docker container (Java application), the call to InetAddress.getLocalHost().getHostName() returns the same name we gave in docker run --name 'myserver'.

Is there a way to let InetAddress.getLocalHost().getHostName() return "localhost" in Java code inside the docker container?

My /etc/hosts in the docker container looks like this: 127.0.0.1 localhost ::1 localhost ip6-localhost ip6-loopback <snip> 172.17.0.5 myserver

1 Answers

Let's use this sample code to validate the same...

import java.net.InetAddress;
import java.net.UnknownHostException;
public class Util {
public static String getHostName() {
    String hostName = "";
    try {
        InetAddress inetAddress = InetAddress.getLocalHost();
        hostName = inetAddress.getHostName();
    } catch (UnknownHostException e) {

    }
    return hostName;
}

public static void main(String[] args) {
    System.out.println(getHostName());
}

}

Let's assume that you are running a docker container in a Box name BOX1

and the docker containerId = 164f1347533a...

This will print 164f1347533a as the Hostname.

To get BOX1, you will have to pass --hostname=BOX1 in the startup command.

Related