Getting container's IP inside a dockerfile

时间:2018-11-27 00:48:39

标签: reactjs api docker

I am running a reactjs app using docker container, and we are using Mock API and UI. I am running those inside a single docker container as 2 separate process. However, in the .env file of the reactjs app the environment variables are mapped to localhost like below :-

REACT_APP_MOCK_API_URL="http://localhost:8080/API"
REACT_APP_MOCK_API_URL_AUTH="http://localhost:8080/API/AUTH"
REACT_APP_MOCK_API_URL_PRESENTATION="http://localhost:8080/API/PRESENTATION"

Since the docker container's IP would be dynamic i need to override it with the dynamic ip that the container will be creating at run time.

May i know the way to do this inside dockerfile ???

PS : I tried assigning the static IP inside the docker file for these environment vars and it works. However, i am not sure how to get the IP dynamically and pass it inside the dockerfile itself .

Please help.

Thanks.

1 个答案:

答案 0 :(得分:1)

从本质上讲,这不是您可以直接在Dockerfile中设置的内容。通常,您通常根本不需要关心容器内部的IP地址:在其他容器中,您应该使用Docker的内部DNS服务,而在容器外部,您可以通过主机的IP地址访问发布的端口(docker run -p选项)

在许多情况下,您可以从HTTP标头中收集足够的信息以在应用程序内构造有效链接。您也许可以将这些变量设置为例如 REACT_APP_MOCK_API_URL="/API";如果相对于应用程序中的其他URL解释了该URL,则它将继承正确的主机名。

如果这些都不起作用,则可以使用入口点脚本来设置这些变量。看起来可能像这样:

#!/bin/sh
if [ -n "$URL_PREFIX" ]; then
  # Set these three variables, if they're not already set
  : ${REACT_APP_MOCK_API_URL:="${URL_PREFIX}/API"}
  : ${REACT_APP_MOCK_API_URL_AUTH:="${URL_PREFIX}/API/AUTH"}
  : ${REACT_APP_MOCK_API_URL_PRESENTATION:="${URL_PREFIX}/API/PRESENTATION"}
  # Export them to other processes
  export REACT_APP_MOCK_API_URL REACT_APP_MOCK_API_URL_AUTH
  export REACT_APP_MOCK_API_URL_PRESENTATION
fi
# Launch the main container command
exec "$@"

在Dockerfile中,您需要COPY将该脚本放入其中并以ENTRYPOINT的身份运行

...
COPY docker-entrypoint.sh /
ENTRYPOINT ["/docker-entrypoint.sh"]
CMD [...]

然后,当您最终运行容器时,可以动态注入URL前缀,包括您选择的任何端口。

docker run -e URL_PREFIX="http://$(hostname):3456" -p 3456:8080 ...

入口点脚本将基于URL_PREFIX变量设置其他变量,然后运行在Dockerfile中设置为CMD或在docker run命令行中命名的命令。 (如果您docker run -it ... sh,入口点将运行,并在最后一步启动交互式外壳程序,这对于调试很有用。)