Skip to content

Angular on AWS with SST

SST를 사용하여 Angular 앱을 생성하고 AWS에 배포하기

AWS에서 SST를 사용한 Angular 배포

Angular 18 SPA를 생성하고, 파일 업로드를 위한 S3 버킷을 추가한 후, SST를 사용해 AWS에 배포해 보겠습니다.

시작하기 전에 AWS 자격 증명을 설정해야 합니다.


1. 프로젝트 생성

프로젝트를 만들어 보겠습니다.

Terminal window
npm install -g @angular/cli
ng new aws-angular
cd aws-angular

스타일은 CSS를 선택하고, SSR은 사용하지 않습니다.

SST 초기화

이제 앱에서 SST를 초기화해 보겠습니다.

Terminal window
npx sst@latest init

이 명령어를 실행하면 프로젝트 루트에 sst.config.ts 파일이 생성됩니다.


2. S3 버킷 추가하기

파일 업로드를 위해 S3 버킷에 공개 access를 허용해 보겠습니다. sst.config.ts 파일을 업데이트하세요.

sst.config.ts
const bucket = new sst.aws.Bucket("MyBucket", {
access: "public"
});

이 코드를 StaticSite 컴포넌트 위에 추가하세요.

이 버킷에 파일을 업로드하기 위해 사전 서명된 URL을 사용할 예정입니다. 이를 통해 파일을 직접 버킷에 업로드할 수 있습니다.

3. API 추가하기

URL을 생성할 간단한 API를 만들어 보겠습니다. Bucket 컴포넌트 아래에 다음 코드를 추가하세요.

sst.config.ts
const pre = new sst.aws.Function("MyFunction", {
url: true,
link: [bucket],
handler: "functions/presigned.handler",
});

이 함수에 버킷을 연결하고 있습니다.

API URL 전달하기

이제 API URL을 Angular 앱에 전달해 보겠습니다. StaticSite 컴포넌트의 build 속성 아래에 다음 코드를 추가하세요.

sst.config.ts
environment: {
NG_APP_PRESIGNED_API: pre.url
}

이 값을 Angular 앱에서 사용하려면 @ngx-env/builder 패키지를 설치합니다.

Terminal window
ng add @ngx-env/builder

개발 모드 시작

개발 모드를 시작하려면 다음 명령어를 실행하세요. 이 명령어는 SST와 여러분의 Angular 앱을 시작합니다.

Terminal window
npx sst dev

실행이 완료되면 사이드바에서 MyWeb을 클릭하고 브라우저에서 Angular 앱으로 이동하세요. 일반적으로 http://localhost:4200에서 확인할 수 있습니다.

3. 파일 업로드 폼 만들기

파일 업로드를 처리할 컴포넌트를 만들어 보겠습니다. src/app/file-upload.component.ts에 다음 내용을 추가합니다.

src/app/file-upload.component.ts
import { Component, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-file-upload',
standalone: true,
imports: [FormsModule],
template: `
<form (ngSubmit)="onSubmit($event)">
<input type="file" name="file">
<button type="submit">Upload</button>
</form>
`,
})
export class FileUploadComponent {
private http = inject(HttpClient);
presignedApi = import.meta.env['NG_APP_PRESIGNED_API'];
async onSubmit(event: Event): Promise<void> {
const file = (event.target as HTMLFormElement)['file'].files?.[0]!;
this.http.get(this.presignedApi, { responseType: 'text' }).subscribe({
next: async (url: string) => {
const image = await fetch(url, {
body: file,
method: "PUT",
headers: {
"Content-Type": file.type,
"Content-Disposition": `attachment; filename="${file.name}"`,
},
});
window.location.href = image.url.split("?")[0];
},
});
}
}

이 코드는 환경 변수에서 미리 서명된 API URL을 가져옵니다. 이 URL에 요청을 보내 미리 서명된 URL을 받고, 그 URL에 파일을 업로드합니다.

template 속성 아래에 styles를 추가해 보겠습니다.

src/app/file-upload.component.ts
styles: [`
form {
color: white;
padding: 2rem;
display: flex;
align-items: center;
justify-content: space-between;
background-color: #23262d;
background-image: none;
background-size: 400%;
border-radius: 0.6rem;
background-position: 100%;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1);
}
button {
appearance: none;
border: 0;
font-weight: 500;
border-radius: 5px;
font-size: 0.875rem;
padding: 0.5rem 0.75rem;
background-color: white;
color: black;
}
button:active:enabled {
background-color: #EEE;
}
`]

HTTP 요청을 보내기 위해 Angular 앱 설정에 프로바이더를 추가해야 합니다. src/app/app.config.tsproviders 목록에 다음을 추가합니다.

src/app/app.config.ts
provideHttpClient(withFetch())

그리고 파일 상단에 import를 추가합니다.

src/app/app.config.ts
import { provideHttpClient, withFetch } from '@angular/common/http';

이제 이 컴포넌트를 앱에 추가해 보겠습니다. src/app/app.component.ts 파일을 다음 내용으로 교체합니다.

src/app/app.component.ts
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { FileUploadComponent } from './file-upload.component';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, FileUploadComponent],
template: `
<main>
<app-file-upload></app-file-upload>
</main>
<router-outlet></router-outlet>
`,
styles: [`
main {
margin: auto;
padding: 1.5rem;
max-width: 60ch;
}
`],
})
export class AppComponent { }

4. 사전 서명된 URL 생성하기

사전 서명된 URL을 생성하는 API를 구현해 보겠습니다. 다음 내용으로 functions/presigned.ts 파일을 생성합니다.

functions/presigned.ts
import { Resource } from "sst";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
export async function handler() {
const command = new PutObjectCommand({
Key: crypto.randomUUID(),
Bucket: Resource.MyBucket.name,
});
return {
statusCode: 200,
body: await getSignedUrl(new S3Client({}), command),
};
}

그리고 npm 패키지를 설치합니다.

Terminal window
npm install @aws-sdk/client-s3 @aws-sdk/s3-request-presigner

브라우저에서 로컬 Angular 앱(http://localhost:4200)으로 이동해 이미지 업로드를 시도해 보세요. 이미지가 업로드되고 다운로드되는 것을 확인할 수 있습니다.


5. 앱 배포하기

이제 여러분의 앱을 AWS에 배포해 보겠습니다.

Terminal window
npx sst deploy --stage production

여기서는 어떤 스테이지 이름을 사용해도 되지만, 프로덕션을 위해 새로운 스테이지를 만드는 것이 좋습니다.


콘솔 연결하기

다음 단계로, 여러분은 SST 콘솔을 설정하여 _git push로 앱을 배포_하고 문제를 모니터링할 수 있습니다.

SST 콘솔 자동 배포

무료 계정을 생성하고 AWS 계정에 연결할 수 있습니다.