Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get docker container name in java code

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.

like image 947
Rajib Biswas Avatar asked May 30 '17 03:05

Rajib Biswas


People also ask

How do I find the id of a docker container?

Find the running container's ID by using the docker ps command. Find the PID number of the first process in the running container by running the docker inspect command. Enter the running container by using the nsenter command.

What is docker container Java?

Docker is the most widely used way to containerize your application. With Docker Hub, it is easy to create and pull pre-created images. This is very convenient as you can use these images from Docker Hub to quickly build an image for your Java application.


1 Answers

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.

like image 96
VonC Avatar answered Sep 28 '22 00:09

VonC