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.

Rajib Biswas
  • 772
  • 10
  • 27

1 Answers1

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.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • 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? – Rajib Biswas May 30 '17 at 04:51
  • @RajibBiswas No: passing the name is the easiest wxay: why can't you set it that way on docker run? – VonC May 30 '17 at 04:52
  • 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. – Rajib Biswas May 30 '17 at 04:55
  • @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. – VonC May 30 '17 at 04:58
  • But what if we don't want to force our customers to provide the container name? – Rajib Biswas May 30 '17 at 05:44