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

Human Khoo
  • 135
  • 3
  • 9
  • 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. – David Maze Jul 26 '18 at 17:38
  • 1
    i need to save the containername in a mysqldb to the running script informations – Human Khoo Jul 26 '18 at 17:40

1 Answers1

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
D. Vinson
  • 1,090
  • 6
  • 8
  • 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" – Danny Dec 16 '18 at 03:33
  • The container name refers to the name given to it in Docker via the `--name` parameter, not an environment variable... – Cerin May 28 '19 at 19:14
  • 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 – jai.maruthi Jun 18 '19 at 07:18
  • Try `$NAME` (case sensitive) – D. Vinson Jun 26 '19 at 05:28
  • 1
    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. – JanFrederik Jun 04 '21 at 17:17