How to get the hostname of the docker host from inside a docker container on that host without env vars

后端 未结 8 1373
时光取名叫无心
时光取名叫无心 2020-12-13 12:13

What are the ways get the docker host\'s hostname from inside a container running on that host besides using environment variables? I know I can pass the hostname as

相关标签:
8条回答
  • 2020-12-13 12:38

    I'm adding this because it's not mentioned in any of the other answers. You can give a container a specific hostname at runtime with the -h directive.

    docker run -h=my.docker.container.example.com ubuntu:latest
    

    You can use backticks (or whatever equivalent your shell uses) to get the output of hosthame into the -h argument.

    docker run -h=`hostname` ubuntu:latest
    

    There is a caveat, the value of hostname will be taken from the host you run the command from, so if you want the hostname of a virtual machine that's running your docker container then using hostname as an argument may not be correct if you are using the host machine to execute docker commands on the virtual machine.

    0 讨论(0)
  • 2020-12-13 12:44

    I know it's an old question, but I needed this solution too, and I acme with another solution.

    I used an entrypoint.sh to execute the following line, and define a variable with the actual hostname for that instance:

    HOST=`hostname --fqdn`
    

    Then, I used it across my entrypoint script:

    echo "Value: $HOST"
    

    Hope this helps

    0 讨论(0)
  • 2020-12-13 12:48

    I ran

    docker info | grep Name: | xargs | cut -d' ' -f2
    

    inside my container.

    0 讨论(0)
  • 2020-12-13 12:49

    You can pass in the hostname as an environment variable. You could also mount /etc so you can cat /etc/hostname. But I agree with Vitaly, this isn't the intended use case for containers IMO.

    0 讨论(0)
  • 2020-12-13 12:59

    Another option that worked for me was to bind the network namespace of the host to the docker.

    By adding:

    docker run --net host
    
    0 讨论(0)
  • 2020-12-13 13:00

    You can easily pass it as an environment variable

    docker run .. -e HOST_HOSTNAME=`hostname` ..
    

    using

    -e HOST_HOSTNAME=`hostname`
    

    will call the hostname and use it's return as an environment variable called HOST_HOSTNAME, of course you can customize the key as you like.

    note that this works on bash shell, if you using a different shell you might need to see the alternative for "backtick", for example a fish shell alternative would be

    docker run .. -e HOST_HOSTNAME=(hostname) ..
    
    0 讨论(0)
提交回复
热议问题