我正在使用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中,当我尝试检索所有env时,我没有从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
答案 0 :(得分:0)
cron加载了它自己的环境变量,解决方法是将env
从容器加载到文件,然后在调用jar文件之前导出该文件。
Dockerfile:
...
#call start.sh to environment variable for cron
CMD /bin/bash /opt/project_dump/start.sh
start.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
execute.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/