简体   繁体   English

如何在启动时动态地将docker容器ip设置为环境变量?

[英]How to Set docker container ip to environment variable dynamically on startup?

I want to export docker container hostname as an environment variable which I can later use in my app. 我想将docker容器主机名导出为环境变量,以后可以在我的应用程序中使用。 In my docker file I call my script "run" as last command 在我的Docker文件中,我将脚本称为“运行”作为最后一个命令

CMD run

The run file is executable and works fine with rest of commands I perform but before them I want to export container hostname to an env. 运行文件是可执行文件,可以与我执行的其他命令配合使用,但是在我想将容器主机名导出到环境之前,它们可以正常工作。 variable as follows 变量如下

"run" File Try 1 “运行”文件尝试1

#!/bin/bash
export DOCKER_MACHINE_IP=`hostname -i`
my_other_commands
exec tail -f /dev/null

But when I enter docker container and check, the variable is not set. 但是当我进入docker容器并检查时,未设置变量。 If I use 如果我用

echo $DOCKER_MACHINE_IP 回声$ DOCKER_MACHINE_IP

in run file after exporting, it shows ip on console when I try 在导出后在运行文件中,当我尝试时它在控制台上显示ip

docker logs 码头工人日志

I also tried sourcing another script from "run" file as follows 我还尝试从“运行”文件中采购另一个脚本,如下所示

"run" File Try 2 “运行”文件尝试2

#!/bin/bash
source ./bin/script
my_other_commands 
exec tail -f /dev/null

and the script again contains the export command. 脚本再次包含导出命令。 But this also does not set the environment variable. 但这也没有设置环境变量。 What I am doing wrong? 我做错了什么?

When you execute a script, any environment variable set by that script will be lost when the script exits. 执行脚本时,脚本退出时,该脚本设置的任何环境变量都会丢失。

But for both the cases you've posted above the environment variable should be accessible for the commands in your scripts, but when you enter the docker container via docker run you will get a new shell, which does not contain your variable. 但是对于您在脚本上方的命令发布的两种情况,环境变量都应该可用于脚本中的命令,但是当您通过docker run输入docker容器时,将获得一个不包含变量的新外壳。

tl;dr Your exported environment variable will only be available to sub shells of the shell which set the variable. tl; dr您导出的环境变量仅可用于设置该变量的shell的子shell。 And if you need it when logging in you should source the ./bin/script file. 并且,如果您在登录时需要它,则应获取./bin/script文件的源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM