docker环境隔离问题-新配置的host在docker容器内没有生效的临时解决方案-通过Java代码在httpclient添加域名与ip的映射解决
昨天发现一个问题,docker容器启动后,在宿主机配置的host没有生效
把镜像删除后重新创建都没有生效,无奈工期太紧先临时解决
临时解决方案-
1.通过Java代码在httpclient添加域名与ip的映射解决
2.在容器启动的时候通过docker run add host的方式添加指定的host
3.在docker容器中的java服务启动的时候把域名和ip写入到docker容器的host中,这里要说一下为什么每次都要写.
docker容器每次构建的时候都回重新生成一份host存放于docker自己的host文件中,因为每次构建的时候可能回改变服务器的ip;
临时方案采用方案1,通过java代码添加域名与ip的映射来解决;
代码如下
@Component
public class HttpUtil {
@ConfigValue("domain")
private String domain;
@ConfigValue("ip")
private String ip;
public String get(String url) {
String result;
if (StringUtils.isEmpty(domain) || StringUtils.isEmpty(ip)) {
result = HttpUtils.get(url);
} else {
result = apigGet(url);
}
return result;
}
public String apigGet(String url) {
HttpHost proxyhost = new HttpHost(ip, 80, "http");
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyhost);
HttpHost targethost = new HttpHost(domain, 80, "http");
System.out.println("executing request to " + targethost + " via " + proxyhost);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).build();
HttpGet get = new HttpGet(url);
get.setConfig(requestConfig);
HttpResponse response = httpclient.execute(targethost, get);
if (response.getStatusLine().getStatusCode() == 200) {
return response.getEntity() != null ? IOUtils.toString(response.getEntity().getContent(), "UTF-8") : null;
} else {
return "response code : " + response.getStatusLine().getStatusCode();
}
} catch (Exception var4) {
Logger.error("HttpUtil HttpUtils get error : ", var4);
return null;
}
}
}
domain=xxx.com
ip=192.168.0.1
domain和ip是通过配置文件配置的属性