N7Legend
N7Legend

Reputation: 91

Is there any way to get the container name inside a container?

Is there any way of getting the container name inside the container in a java programm using processBuilder ?

Example: the command docker run -it --name AppContainer RetrieveNameApp should return AppContainer

Thank you !

Upvotes: 1

Views: 669

Answers (1)

Javier Buzzi
Javier Buzzi

Reputation: 6818

I just ran into this use case, but the examples given were docker centric, not to mention they wanted you to expose docker.sock which... it's bad form/security risk.

Prerequisite:

apt update
apt install dnsutils

Or...

yum install bind-utils

Lastly:

hostname -I | xargs -L 1 -d ' ' dig +noall +answer -x | awk '{print $5}' | cut -f2 -d _ | sort | uniq

If you run this inside the running docker container, you'll get the name.


Working examples:

(docker-compose) Note: you can copy this EXACTLY into your shell. This is for demonstration purposes ONLY, and i DO NOT suggest you write your docker-compose.yaml like this.

docker-compose -f <(cat << EOF
services:
    this-is-my-name-every-body:
      image: python:3.6
EOF
) run --rm this-is-my-name-every-body bash -c "apt update &>/dev/null; apt install -y dnsutils &>/dev/null; hostname -I | xargs -L 1 -d ' ' dig +noall +answer -x | awk '{print \$5}' | cut -f2 -d _ | sort | uniq"

(docker) Note: in order to be able to do a reverse lookup the docker run command MUST have a --network, and that requires you to docker network create it (must be only ran once).

docker network create temp-net
docker run --rm -it --network temp-net --name hello-every-body python:3.6 bash -c "apt update &>/dev/null; apt install -y dnsutils &>/dev/null; hostname -I | xargs -L 1 -d ' ' dig +noall +answer -x | awk '{print \$5}' | cut -f2 -d _ | sort | uniq"

Upvotes: 1

Related Questions