Get Environment Variable from Docker Container

后端 未结 10 2001
花落未央
花落未央 2020-12-12 11:12

What\'s the simplest way to get an environment variable from a docker container that has not been declared in the Dockerfile?

For instance, an environment v

10条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-12 11:58

    The downside of using docker exec is that it requires a running container, so docker inspect -f might be handy if you're unsure a container is running.

    Example #1. Output a list of space-separated environment variables in the specified container:

    docker inspect -f \
       '{{range $index, $value := .Config.Env}}{{$value}} {{end}}' container_name
    

    the output will look like this:

    ENV_VAR1=value1 ENV_VAR2=value2 ENV_VAR3=value3
    

    Example #2. Output each env var on new line and grep the needed items, for example, the mysql container's settings could be retrieved like this:

    docker inspect -f \
        '{{range $index, $value := .Config.Env}}{{println $value}}{{end}}' \
        container_name | grep MYSQL_
    

    will output:

    MYSQL_PASSWORD=secret
    MYSQL_ROOT_PASSWORD=supersecret
    MYSQL_USER=demo
    MYSQL_DATABASE=demodb
    MYSQL_MAJOR=5.5
    MYSQL_VERSION=5.5.52
    

    Example #3. Let's modify the example above to get a bash friendly output which can be directly used in your scripts:

    docker inspect -f \
       '{{range $index, $value := .Config.Env}}export {{$value}}{{println}}{{end}}' \
       container_name | grep MYSQL
    

    will output:

    export MYSQL_PASSWORD=secret
    export MYSQL_ROOT_PASSWORD=supersecret
    export MYSQL_USER=demo
    export MYSQL_DATABASE=demodb
    export MYSQL_MAJOR=5.5
    export MYSQL_VERSION=5.5.52
    

    If you want to dive deeper, then go to Go’s text/template package documentation with all the details of the format.

提交回复
热议问题