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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With