Maven无法连接到docker内的networking

我想克隆一个git项目,并在mvn package执行mvn package 。 但是maven无法连接到networking来下载依赖关系。 这是Dockerfile

 FROM java:8 FROM maven ADD id_rsa /root/.ssh/id_rsa ADD known_hosts /root/.ssh/known_hosts RUN git clone git@myhub.mygithub.com:project/myapp.git WORKDIR myapp RUN mvn package 

这是maven构build命令:

 sudo docker build --build-arg http_proxy=http://proxy.in.my.com:80 --build-arg https_proxy=http://proxy.in.my.com:80 --build-arg ftp_proxy=http://proxy.in.my.com:80 --build-arg no_proxy=localhost,127.0.0.1,.us.my.com,.my.com -t myapp . 

我在mvn package得到以下错误:

 Downloading: https://repo.maven.apache.org/maven2/org/jacoco/jacoco-maven-plugin/0.7.6.201602180812/jacoco-maven-plugin-0.7.6.201602180812.pom [ERROR] Plugin org.jacoco:jacoco-maven-plugin:0.7.6.201602180812 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.jacoco:jacoco-maven-plugin:jar:0.7.6.201602180812: Could not transfer artifact org.jacoco:jacoco-maven-plugin:pom:0.7.6.201602180812 from/to central (https://repo.maven.apache.org/maven2): Network is unreachable (connect failed) -> [Help 1] 

问题是你正在传递构build参数,但没有在你的Dockerfile中的任何地方使用它们。 传递参数与传递一个Environmentvariables不同。

所以更新你的dockerfile。 另外你有两个FROM是有效的,因为现在多阶段构build,但你只需要在这个maven。

你可以用两种方法build立你的文件

 FROM maven ARG http_proxy ENV http_proxy=${http_proxy} RUN git clone git@myhub.mygithub.com:project/myapp.git 

这将设置完整的图像的环境,当你运行图像的代理将已经设置它的容器。 如果你只需要做这个做git克隆然后使用下面的方法

 FROM maven ARG http_proxy RUN http_proxy=${http_proxy} git clone git@myhub.mygithub.com:project/myapp.git 

这只会设置克隆的参数,您的图像在运行时不会使用代理。

编辑-1

Maven似乎不尊重http_proxy。 所以你需要在maven config中自己指定代理。 configuration位于maven镜像内的/usr/share/maven/conf/settings.xml

有一个代理的部分是默认注释的

  |--> <proxies> <!-- proxy | Specification for one proxy, to be used in connecting to the network. | <proxy> <id>optional</id> <active>true</active> <protocol>http</protocol> <username>proxyuser</username> <password>proxypass</password> <host>proxy.host.net</host> <port>80</port> <nonProxyHosts>local.net|some.host.com</nonProxyHosts> </proxy> --> </proxies> 

取消注释并在主机目录中创buildconfiguration文件。 在Dockerfile中使用COPY命令复制文件。 现在maven也应该使用代理

您需要更新Maven设置文件“〜/ .m2 / settings.xml”来添加代理configuration。

 <proxies> <proxy> <id>optional</id> <active>true</active> <protocol>$PROXY_PROTOCOL</protocol> <username>$PROXY_USER</username> <password>$PROXY_PASS</password> <host>$PROXY_HOST</host> <port>$PROXY_PORT</port> <nonProxyHosts>$NO_PROXY</nonProxyHosts> </proxy> </proxies> 

看看下面的https://github.com/alirizasaral/Maven-with-Proxy/ 。 你可以做一些非常类似的事情,你添加一个模板maven settings.xml,你可以在Dockerfile中执行一个envsubst步骤,在这个步骤中将代理值占位符replace为以构buildparameter passing的值。

这比在settings.xml中硬编码代理值更好,因为您可能想要使用不同的代理构build映像。