Skip to content

Express on AWS with SST

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

Express를 AWS에 SST로 배포하기

Express로 앱을 만들고, 파일 업로드를 위한 S3 버킷을 추가한 다음, SST를 사용해 AWS에 컨테이너로 배포해 보겠습니다.

시작하기 전에 AWS 자격 증명을 설정하세요.


예제

여러분이 참고할 수 있는 다른 Express 예제도 몇 가지 있습니다.


1. 프로젝트 생성

Express 앱을 만들어 보겠습니다.

Terminal window
mkdir aws-express && cd aws-express
npm init -y
npm install express

Express 초기화

루트에 index.mjs 파일을 추가하여 앱을 생성하세요.

index.mjs
import express from "express";
const PORT = 80;
const app = express();
app.get("/", (req, res) => {
res.send("Hello World!")
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});

SST 초기화

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

Terminal window
npx sst@latest init
npm install

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


2. 서비스 추가하기

Express 앱을 배포하기 위해 Amazon ECS와 함께 AWS Fargate 컨테이너를 추가해 보겠습니다. sst.config.ts 파일을 업데이트하세요.

sst.config.ts
async run() {
const vpc = new sst.aws.Vpc("MyVpc");
const cluster = new sst.aws.Cluster("MyCluster", { vpc });
cluster.addService("MyService", {
loadBalancer: {
ports: [{ listen: "80/http" }],
},
dev: {
command: "node --watch index.mjs",
},
});
}

이 코드는 VPC와 ECS 클러스터를 생성하고, 여기에 Fargate 서비스를 추가합니다.

dev.command는 SST에게 개발 모드에서 Express 앱을 로컬에서 실행하도록 지시합니다.


개발 모드 시작

다음 명령어를 실행해 개발 모드를 시작합니다. 이 명령어는 SST와 여러분의 Express 앱을 실행합니다.

Terminal window
npx sst dev

실행이 완료되면 사이드바에서 MyService를 클릭하고 브라우저에서 Express 앱을 열어보세요.

3. S3 버킷 추가하기

파일 업로드를 위해 S3 버킷을 추가해 보겠습니다. Vpc 컴포넌트 아래에 다음 코드를 sst.config.ts 파일에 추가하세요.

sst.config.ts
const bucket = new sst.aws.Bucket("MyBucket");

버킷 연결하기

이제 버킷을 컨테이너에 연결합니다.

sst.config.ts
cluster.addService("MyService", {
// ...
link: [bucket],
});

이렇게 하면 Express 앱에서 버킷을 참조할 수 있습니다.


4. 파일 업로드

/ 라우트로 POST 요청을 보내 S3 버킷에 파일을 업로드하려고 합니다. index.mjs 파일의 Hello World 라우트 아래에 이를 추가해 보겠습니다.

index.mjs
app.post("/", upload.single("file"), async (req, res) => {
const file = req.file;
const params = {
Bucket: Resource.MyBucket.name,
ContentType: file.mimetype,
Key: file.originalname,
Body: file.buffer,
};
const upload = new Upload({
params,
client: s3,
});
await upload.done();
res.status(200).send("File uploaded successfully.");
});

필요한 모듈을 임포트합니다. 아래 추가 모듈을 사용할 것입니다.

index.mjs
import multer from "multer";
import { Resource } from "sst";
import { Upload } from "@aws-sdk/lib-storage";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import {
S3Client,
GetObjectCommand,
ListObjectsV2Command,
} from "@aws-sdk/client-s3";
const s3 = new S3Client({});
const upload = multer({ storage: multer.memoryStorage() });

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

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

5. 파일 다운로드

S3 버킷에서 가장 최신 파일을 다운로드할 수 있는 /latest 라우트를 추가하겠습니다. 이 코드를 index.mjs 파일의 업로드 라우트 아래에 추가합니다.

index.mjs
app.get("/latest", async (req, res) => {
const objects = await s3.send(
new ListObjectsV2Command({
Bucket: Resource.MyBucket.name,
}),
);
const latestFile = objects.Contents.sort(
(a, b) => b.LastModified - a.LastModified,
)[0];
const command = new GetObjectCommand({
Key: latestFile.Key,
Bucket: Resource.MyBucket.name,
});
const url = await getSignedUrl(s3, command);
res.redirect(url);
});

앱 테스트하기

파일을 업로드하려면 프로젝트 루트에서 다음 명령어를 실행하세요.

Terminal window
curl -F file=@package.json http://localhost:80/

이 명령어는 package.json 파일을 업로드합니다. 이제 브라우저에서 http://localhost:80/latest로 이동하면 방금 업로드한 내용을 확인할 수 있습니다.


5. 앱 배포하기

앱을 배포하기 위해 먼저 Dockerfile을 추가합니다.

Dockerfile
FROM node:lts-alpine
WORKDIR /app/
COPY package.json /app
RUN npm install
COPY index.mjs /app
ENTRYPOINT ["node", "index.mjs"]

이 파일은 Express 앱을 Docker 이미지로 빌드합니다.

루트에 .dockerignore 파일도 추가합니다.

.dockerignore
node_modules

이제 Docker 이미지를 빌드하고 배포하려면 다음 명령어를 실행합니다.

Terminal window
npx sst deploy --stage production

여기서는 어떤 스테이지 이름을 사용해도 되지만, 프로덕션을 위해 새로운 스테이지를 만드는 것이 좋습니다. 이 명령어는 Express 앱이 Fargate 서비스로 배포된 URL을 제공합니다.

Terminal window
Complete
MyService: http://jayair-MyServiceLoadBala-592628062.us-east-1.elb.amazonaws.com

콘솔 연결하기

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

SST 콘솔 자동 배포

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