Spring boot(ec2) + S3: Bucket does not exist error. (AWS EC2에서 S3 bucket을 찾지 못합니다.)

1

I created a project that works with S3 using Spring boot. It worked fine in both local and other deployment environments (cloudtype), but an error occurred that the bucket did not exist in the ec2 environment.

I checked several times for typos. It still works well with the same bucket in different deployments.

-- Korean -- Spring boot를 이용해서 S3와 연동하는 프로젝트를 생성했습니다. 로컬과 다른 배포환경(cloudtype)에서는 모두 정상적으로 작동했지만, ec2 환경에서는 버킷이 존재하지 않는다는 오류가 발생했습니다.

오타가 없는지 여러번 확인했습니다. 여전히 다른 배포환경에서는 동일한 버킷으로 잘 작동합니다.

Gradle dependency -> implementation 'org.springframework.cloud:spring-cloud-starter-aws:2.2.6.RELEASE'

S3 Service

@Service
@RequiredArgsConstructor
public class S3FileServiceImpl implements MyFileService{

    private final AmazonS3 amazonS3;

    @Value("${cloud.aws.s3.bucket}")
    private String bucket;

    @Override
    public UploadFile uploadFile(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String storeFileName = UUID.randomUUID().toString();

        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(file.getSize());
        metadata.setContentType(file.getContentType());

        amazonS3.putObject(bucket, storeFileName, file.getInputStream(), metadata);
        return new UploadFile(originalFilename, storeFileName);
    }
}

application.yml

cloud:
  aws:
    s3:
      bucket: ${PROD_S3_BUCKET}
    credentials:
      access-key: ${PROD_S3_ACCESS_KEY}
      secret-key: ${PROD_S3_SECRET_KEY}
    region:
      static: "ap-northeast-2"
      auto: false
    stack:
      auto: false

Error message: com.amazonaws.services.s3.model.AmazonS3Exception: The specified bucket does not exist (Service: Amazon S3; Status Code: 404; Error Code: NoSuchBucket; Request ID: {SECRET}; S3 Extended Request ID: {SECRET}; Proxy: null)

2개 답변
2

안녕하세요.

EC2 에서 Springboot 애플리케이션을 실행할 때 NoSuchBucket 에러가 발생한 것 같습니다.

우선 로컬 환경과 EC2 인스턴스에서 동일한 조건으로 수행된 것인지 확인해 봐야합니다.

[1]

첨부하신 application.yml 은 다음과 같습니다

  • cloud.aws.s3.bucket : S3 버킷명
  • cloud.aws.credentials.access-key : AWS IAM User 의 Access Key
  • cloud.aws.credentials.secret-key : AWS IAM User 의 Secret key
  • cloud.aws.region.static: S3 버킷의 AWS Region

또한 AWS IAM에서 User 를 생성하여 S3 에 대한 적절한 Policy 를 추가하셔야 합니다.

[2]

보다 정확한 에러 메시지를 확인하기 위해 ExceptionHandler 를 다음과 같이 추가할 수 있습니다.

GlobalExceptionHandler.java

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {


 @ExceptionHandler(Exception.class)
 protected ResponseEntity<ErrorResponse> handleException(AmazonS3Exception e) {
 log.error("AmazonS3Exception", e);

 final ErrorResponse response = ErrorResponse.create(e, HttpStatusCode.valueOf(500), e.getErrorResponseXml());
 return ResponseEntity.internalServerError().body(response);
 }
}

같은 요청을 보냈을 시, GlobalExceptionHandler 의 다음과 같은 에러 메시지 (HTTP Response) 를 받게 됩니다.

{
 "statusCode":"INTERNAL_SERVER_ERROR",
 "headers”: {}, 
 ”detailMessageCode":"problemDetail.com.amazonaws.services.s3.model.AmazonS3Exception",
 "detailMessageArguments":null,
 "titleMessageCode":"problemDetail.title.com.amazonaws.services.s3.model.AmazonS3Exception",
 "body":
 {
 "type":"about:blank",
 "title":"Internal Server Error",
 "status":500,
 "detail":
 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Error><Code>NoSuchBucket</Code><Message>The specified bucket does not exist</Message><BucketName>{요청한 S3 버킷명}</BucketName><RequestId>{RequestID}</RequestId><HostId>{HostID}</HostId></Error>"
 }
}

에러 메시지를 통해 요청한 서버에서 응답한 S3 버킷명이 무엇인지 확인해 봐야 합니다.

body 의 json 객체에서 detail 은 AmazonS3Exception 에서 반환하는 내용 XML 파일 입니다.

<BucketName>{요청한 S3 버킷명}</BucketName> 을 참고하여 실제로 요청한 S3 버킷명이 맞는지 확인해보세요.

profile picture
Ayeon_K
답변함 7달 전
0

안녕하세요.

어플리케이션 실행 후 S3 오류 발생하면 CloudTrail 에 가셔서 최근 호출된 API 중에 S3 관련 API 들을 찾아보시고 어떤 오류가 남아있는지 한번 확인해보세요.

도움이 될만한 오류내용을 찾지 못하셨다면 error message 에 포함된 RequestID, S3 Extended request ID 등을 support case 로 올려서 분석요청을 해보셔야 할 것 같습니다.

별다른 문제가 없는데 NoSuchBucket 이 자주 발생하는 경우는 다른 리전으로 연결되는 경우 주로 많이 발생합니다.

AWS
Hyeon
답변함 8달 전

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인

관련 콘텐츠