4

I need to get the containers name, from within the running container in python

i could easily get the container id from inside the container in python with

bashCommand = """head -1 /proc/self/cgroup|cut -d/ -f3"""
output = subprocess.check_output(['bash','-c', bashCommand])
print output

now i need the containername

2
  • What would you do with this information if you had it? A process in a container has a pretty limited ability to interact with its outside world. Commented Jul 26, 2018 at 17:38
  • 1
    i need to save the containername in a mysqldb to the running script informations Commented Jul 26, 2018 at 17:40

1 Answer 1

2

Just set the Name at runtime like:

docker run --name MYCOOLCONTAINER alpine:latest

Then:

bashCommandName = `echo $NAME`

output = subprocess.check_output(['bash','-c', bashCommandName]) 

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

5 Comments

This got me on the right track (so thank you!), but for people still struggling, the syntax that worked for me was --name container_name, not NAME="CONTAINERNAME"
The container name refers to the name given to it in Docker via the --name parameter, not an environment variable...
Can I do this on a windows container? When i try 'hostname' on powershell, I get the container id. But get error for 'name' or $name
Try $NAME (case sensitive)
This doesn't work for me. Docker 20.10.6 on Ubuntu 20.04: Start the container with an interactive shell: docker run -it --rm --name MYCOOLCONTAINER alpine:latest sh. There, I run set to view all environment variables. However none contains MYCOOLCONTAINER.

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.