来自Fargate集群上AWS ECS docker容器中运行的Java应用程序的UnknownHostException

时间:2018-01-29 19:19:35

标签: java docker aws-fargate

我有一个大型Java应用程序,我正在尝试在AWS中的fargate集群上运行。图像在本地计算机的docker上成功运行。当我在fargate中运行它时它成功启动,但最终遇到以下错误,之后应用程序卡住了:

! java.net.UnknownHostException: 690bd678bcf4: 690bd678bcf4: Name or service not known
! at java.net.InetAddress.getLocalHost(InetAddress.java:1505) ~[na:1.8.0_151]
! at tracelink.misc.SingletonTokenDBO$.<init>(SingletonTokenDBO.scala:34) ~[habari.jar:8.4-QUARTZ-SNAPSHOT]
! at tracelink.misc.SingletonTokenDBO$.<clinit>(SingletonTokenDBO.scala) ~[habari.jar:8.4-QUARTZ-SNAPSHOT]
!... 10 common frames omitted
Caused by: ! java.net.UnknownHostException: 690bd678bcf4: Name or service not known
! at java.net.Inet4AddressImpl.lookupAllHostAddr(Native Method) ~[na:1.8.0_151]
! at java.net.InetAddress$2.lookupAllHostAddr(InetAddress.java:928) ~[na:1.8.0_151]
! at java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1323) ~[na:1.8.0_151]
! at java.net.InetAddress.getLocalHost(InetAddress.java:1500) ~[na:1.8.0_151]
!... 12 common frames omitted

Scala代码的违规行是:

  private val machineName = InetAddress.getLocalHost().getHostName()

一些初步研究表明,错误与容器中/ etc / hosts文件的内容有关。所以我创建了一个小的测试程序,它表现出与我的真实应用程序相同的行为,并且还将/ etc / hosts的内容转储到stdout:

import java.net.*;
import java.io.*;

public class NetworkTest {
   public static void main(String[] args) throws InterruptedException, IOException, FileNotFoundException {
      while(true) {
         networkDump();
         Thread.sleep(10000);
      }
   }

   private static void networkDump() throws IOException, FileNotFoundException {
      System.out.println("/etc/hosts:");
      System.out.println("");

      FileReader f = new FileReader("/etc/hosts");
      BufferedReader reader = new BufferedReader(f);
      String line = null;
      while((line = reader.readLine()) != null) {
         System.out.println(line);
      }
      System.out.println("");

      dumpHostname();
   }

   private static void dumpHostname() {
      try {
         String hostname = InetAddress.getLocalHost().getHostName();
         System.out.printf("Hostname: %s\n\n", hostname);
      } catch(UnknownHostException e) {
         System.out.println(e.getMessage());
      }
   }
}

Dockerfile:

FROM openjdk:8

WORKDIR /site
ADD . /site

CMD ["java", "NetworkTest"]

我从AWS获得的输出如下:

/etc/hosts:
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

3a5a4271a6e3: 3a5a4271a6e3: Name or service not known

与在本地计算机上使用docker运行的输出相比:

> docker run networktest

/etc/hosts:
127.0.0.1   localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.4  82691e2fb948

Hostname: 82691e2fb948

未获得异常的本地版本在/ etc / hosts中有一个主机名条目,而AWS主机文件没有主机名条目。我已经尝试添加一个/etc/rc.local文件来手动将主机名添加到localhost行的末尾,只需在Dockerfile中添加一个RUN命令来执行相同的操作。两者都没有任何影响。

有没有人知道是否有办法配置图像或ECS任务定义以在AWS中正确配置主机名?

4 个答案:

答案 0 :(得分:4)

通过执行以下命令将主机名指向127.0.0.1:

echo "127.0.0.1 $HOSTNAME" >> /etc/hosts

为我解决了这个问题。

我正在使用Docker Compose。所以我有一个docker-compose.yml这样的文件:

version: '2'

services:
  myservice:
    command: ["/set-hostname.sh", "--", "/run-service.sh"]

然后set-hostname.sh文件如下所示:

#!/bin/bash

set -e

shift
cmd="$@"

echo "127.0.0.1 $HOSTNAME" >> /etc/hosts

exec $cmd

答案 1 :(得分:1)

与我长期困扰的问题完全相同。这个解决方案对我有用:

ENTRYPOINT ["/bin/sh", "-c" , "echo 127.0.0.1 $HOSTNAME >> /etc/hosts && exec mvn spring-boot:run"]

答案 2 :(得分:0)

所以,我遇到了完全相同的问题,事情是,正如你已经提到的那样,主机名没有多大意义。 获取可以在VPC中看到的实际实例IP的唯一方法是使用AWS任务元数据API,在我的例子中我做了。 https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-metadata-endpoint.html

我已连接以下代码来获取localhost IP:

try {
            final ResponseEntity<String> taskInfoResponse = this.restTemplate.getForEntity("http://169.254.170.2/v2/metadata", String.class);
            log.info("Got AWS task info: {}", taskInfoResponse);
            log.info("Got AWS task info: {}", taskInfoResponse.getBody());
            if (taskInfoResponse.getStatusCode() == HttpStatus.OK) {
                try {
                    final ObjectNode jsonNodes = this.objectMapper.readValue(taskInfoResponse.getBody(), ObjectNode.class);
                    final JsonNode jsonNode = jsonNodes.get("Containers")
                            .get(0).get("Networks")
                            .get(0)
                            .get("IPv4Addresses").get(0);
                    log.info("Got IP to use: {}", jsonNode);
                    if (jsonNode != null) {
                        awsTaskInfo.setTaskAddress(InetAddress.getByName(jsonNode.asText()));
                    }
                } catch (IOException e) {
                    throw new IllegalArgumentException(e);
                }
            } else {
                awsTaskInfo.setTaskAddress(InetAddress.getLoopbackAddress());
            }
        }catch (ResourceAccessException e){
            log.error("Failed to fetch AWS info", e);
            awsTaskInfo.setTaskAddress(InetAddress.getLoopbackAddress());
        }

答案 3 :(得分:0)

在尝试从Lambda访问S3和SQS时,我遇到了相同的问题。解决方案是在创建客户端实例时不指定区域,而是:

SqsAsyncClient.builder()
                .region(Region.of(region))
                .build();

执行此操作:

SqsAsyncClient.create();