1

我正在使用docker-maven-plugin并且根据文档我需要通过<envPropertyFile>. 所以 pom.xml 中的插件看起来像

<configuration>
  <images>
    <image>
      <build>
        ...
      </build>
      <run>
         <envPropertyFile>${project.basedir}/local/local.properties</envPropertyFile>
      </run>
    </image>
  </images>
</configuration>

我有以下值的 local.properties,

TIME_COUNT=1000 
REST=10

在我的 java 项目中,我将这些值读为 System.getenv("TIME_COUNT"); #which returns null.

故障排除:
1.当我检查容器内的环境时,我看到TIME_COUNT=1000 and REST=10.

docker exec -it CONTAINER_ID bash
env

2.当我执行

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

我看到所有 env 值(即 TIME_COUNT=1000, REST=10 )

3.在我的 java 中,当我尝试检索所有环境时,我没有从 local.properties 或我可以通过执行在容器内看到的默认值获得任何 env 值env

StringBuilder sb = new StringBuilder();
Map<String, String> env = System.getenv();
  for (String key : env.keySet()) {
      sb.append(key + ": " + env.get(key)  + "\n");
  }
System.out.println(sb.toString());

4.我还尝试传递如下所述的 env 变量,它覆盖了容器中的值,但 jar 文件仍然抛出 null。

docker exec -e TIME_COUNT=12 -it CONTAINER_ID bash
4

1 回答 1

0

cron 加载它自己的环境变量,解决方法是将envfrom 容器加载到文件中,然后在调用 jar 文件之前导出该文件。

Dockerfile:

...
#call start.sh to environment variable for cron
CMD /bin/bash /opt/project_dump/start.sh

开始.sh:

# export all environment variables but `no_proxy` to use in cron.
# Note: no_proxy throws error while exporting due to formatting, envs.sh is created with export environment variables.
env | sed '/no_proxy/d' | sed 's/^\(.*\)$/export \1/g' > /root/envs.sh
chmod +x /root/envs.sh

# Run the cron command on container startup in foreground.
# Note: -n (foreground) keeps the container running instead of exiting once the crond is ran.
crond -n

执行.sh:

#!/bin/bash
/usr/lib/jvm/default-java/bin/java -jar /opt/project_dump/project_name.jar
#emptyline

crontab.txt:

#!/bin/bash
#calls environment script, execute script to call jar
*  *  * * *  root . /root/envs.sh;/opt/project_dump/execute.sh
#emptyline

参考:
1. https://github.com/citta-lab/docker/tree/master/dockerCron
2. http://dev.im-bot.com/docker-cron/

于 2018-01-15T15:18:04.227 回答