1

我在 docker-compose 文件中定义了两个容器:

 
 tomcat_webserver_api:
  image: tomcat:8
  volumes:
   - ./API/Docker/API.war:/usr/local/tomcat/webapps/API.war
  ports:
    - "8080:8080"
  depends_on:
   - mysql_database

 tomcat_webserver_anwendung:
  image: tomcat:8
  ports:
   - "8081:8080"
  volumes:
   - ./Anwendung/Docker/Anwendung.war:/usr/local/tomcat/webapps/Anwendung.war
  depends_on:
   - tomcat_webserver_api
  environment:
    API_HOST: tomcat_webserver_api
    API_PORT: 8080

现在我想使用http://tomcat_webserver_api:8080/API/restaurants/WochentagHttpURLConnection 从 Java Web 应用程序内部访问 URL。

问题:它返回 400 错误

java.io.IOException: Server returned HTTP response code: 400 for URL: http://tomcat_webserver_api:8080/API/restaurants/Wochentag

代码就是这样(当我尝试通过 curl 连接到 URL 时,标题几乎相同 - 这在容器内有效):


    URL api = UriBuilder.fromUri("http://" + "tomcat_webserver_api" + ":" + "8080" +"/API/restaurants/RestaurantSpeisen").build().toURL();

    System.setProperty("http.agent", "curl/7.52.1");

    HttpURLConnection connection = (HttpURLConnection) api.openConnection();
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Host", "localhost");
    connection.setRequestProperty("User-Agent", "curl/7.52.1");
    connection.connect();

    BufferedReader in = new BufferedReader(new             InputStreamReader(connection.getInputStream(), "UTF-8"));

如果我尝试连接到http://172.20.0.3:8080/API/restaurants/Wochentag我得到一个 200-ok HTTP 响应代码和 JSON 数据。

如果我执行 API 容器并检查日志,我可以看到 400 GET-Request。

为什么会这样?

http://172.20.0.3:8080/API/restaurants/Wochentag- 工作 http://tomcat_webserver_api:8080/API/restaurants/Wochentag- 不工作但没有 404 错误

4

2 回答 2

3

我和你有同样的问题,显然下划线不允许作为虚拟主机,尝试删除它,例如,只使用 tomcatwebserverapi,应该可以解决你的问题。

请参阅(域名)子域中是否可以包含下划线“_”?有关主机名中有效字母的更多信息。

于 2018-09-17T09:09:16.330 回答
0

请尝试使用明确的容器名称:

tomcat_webserver_api:
  image: tomcat:8
  container_name: tomcat_webserver_api
  volumes:
   - ./API/Docker/API.war:/usr/local/tomcat/webapps/API.war
  ports:
    - "8080:8080"
  depends_on:
   - mysql_database

tomcat_webserver_anwendung:
  container_name: tomcat_webserver_app
  image: tomcat:8
  ports:
   - "8081:8080"
  volumes:
   - ./Anwendung/Docker/Anwendung.war:/usr/local/tomcat/webapps/Anwendung.war
  depends_on:
   - tomcat_webserver_api
  environment:
    API_HOST: tomcat_webserver_api
    API_PORT: 8080

“仅限本地”配置需要明确的容器名称来激活 Docker 的名称查找机制。在 Swarm 模式下,您不需要设置容器名称。

于 2018-08-02T21:09:24.517 回答