5

If I am running a java application inside a Docker container and I want to fetch the name of the running docker container (inside which my java application is running) from the same java application code, what is the way to get the container name through java code?

Please note that I want to have the java code in the same java application which is running inside the container.

2 Answers 2

6

You could make sure you have the docker.sock mounted, and call docker inspect from there (since you can call docker command with Java)

But that seems overly complex (and relies on hostname being not overriden when launching the container: it does not work in edge cases)

A much simpler solution would be to pass the container name as an environment variable when running said container:

docker run -e name=<containerName> --tag <containerName> ...

That way, you can from Java query an environment variable that you have set yourself when starting the container.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for your answer. But what if I don't want to pass the container name while running docker run. Is there any easy way to find the container name from java code?
@RajibBiswas No: passing the name is the easiest wxay: why can't you set it that way on docker run?
Because we as a product, provide the base image to our customers and then they create their own application image on top of our base image and run the containers. So it is not us who is going to do docker run, our customer are going to do that. So I cannot force my customer to do --name while doing docker run. I hope you understand my problem now.
@RajibBiswas but you can force your container to stop if it does not detect that environment variable: that way, the client will realize he/she has to set it.
But what if we don't want to force our customers to provide the container name?
0

You can use InetAddress.getLocalHost().getHostName() from java.net.InetAddress package to achieve this.

Sample Code:

try {
    System.out.println("Container name: " +  InetAddress.getLocalHost().getHostName());
} catch (UnknownHostException e) {
    System.out.println("Error getting container name");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.