

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 배포 매니페스트를 사용하여 Express 서버 배포
<a name="deploy-express-server"></a>

이 예시에서는 Amplify Hosting 배포 사양을 참조하여 기본 Express 서버를 배포하는 방법을 설명합니다. 제공된 배포 매니페스트를 활용하여 라우팅, 컴퓨팅 리소스 및 기타 구성을 지정할 수 있습니다.

**Amplify Hosting에 배포하기 전에 로컬로 Express 서버 설정**

1. 프로젝트의 새 디렉터리를 만들고 Express와 Typescript를 설치합니다.

   ```
   mkdir express-app
   cd express-app
    
   # The following command will prompt you for information about your project
   npm init
    
   # Install express, typescript and types
   npm install express --save
   npm install typescript ts-node @types/node @types/express --save-dev
   ```

1. 프로젝트의 루트에 다음과 같은 콘텐츠가 포함된 `tsconfig.json` 파일을 추가합니다.

   ```
   {
     "compilerOptions": {
       "target": "es6",
       "module": "commonjs",
       "outDir": "./dist",
       "strict": true,
       "esModuleInterop": true,
       "skipLibCheck": true,
       "forceConsistentCasingInFileNames": true
     },
     "include": ["src/**/*.ts"],
     "exclude": ["node_modules"]
   }
   ```

1. 프로젝트 루트에 `src`라는 디렉터리를 만듭니다.

1. `src` 디렉터리에 `index.ts` 파일을 만듭니다. 이 파일이 애플리케이션에서 Express 서버가 시작되는 진입점이 됩니다. 포트 3000에서 수신 대기하도록 서버를 구성해야 합니다.

   ```
   // src/index.ts
   import express from 'express';
    
   const app: express.Application = express();
   const port = 3000;
    
   app.use(express.text());
    
   app.listen(port, () => {
     console.log(`server is listening on ${port}`);
   });
    
   // Homepage
   app.get('/', (req: express.Request, res: express.Response) => {
     res.status(200).send("Hello World!");
   });
    
   // GET
   app.get('/get', (req: express.Request, res: express.Response) => {
     res.status(200).header("x-get-header", "get-header-value").send("get-response-from-compute");
   });
    
   //POST
   app.post('/post', (req: express.Request, res: express.Response) => {
     res.status(200).header("x-post-header", "post-header-value").send(req.body.toString());
   });
    
   //PUT
   app.put('/put', (req: express.Request, res: express.Response) => {
     res.status(200).header("x-put-header", "put-header-value").send(req.body.toString());
   });
    
   //PATCH
   app.patch('/patch', (req: express.Request, res: express.Response) => {
     res.status(200).header("x-patch-header", "patch-header-value").send(req.body.toString());
   });
    
   // Delete
   app.delete('/delete', (req: express.Request, res: express.Response) => {
     res.status(200).header("x-delete-header", "delete-header-value").send();
   });
   ```

1. 다음과 같은 스크립트를 `package.json` 파일에 추가합니다.

   ```
   "scripts": {
     "start": "ts-node src/index.ts",
     "build": "tsc",
     "serve": "node dist/index.js"
   }
   ```

1. 프로젝트의 루트에 `public`이라는 디렉터리를 만듭니다. 그런 다음에 다음과 같은 콘텐츠가 포함된 `hello-world.txt`라는 파일을 만듭니다.

   ```
   Hello world!
   ```

1. 프로젝트 루트에 다음과 같은 콘텐츠가 포함된 `.gitignore` 파일을 추가합니다.

   ```
   .amplify-hosting
   dist
   node_modules
   ```

**Amplify 배포 매니페스트 설정**

1. 프로젝트의 루트 디렉터리에 `deploy-manifest.json`이라는 파일을 만듭니다.

1. 다음 매니페스트를 복사하여 `deploy-manifest.json` 파일에 붙여넣습니다.

   ```
   {
     "version": 1,
     "framework": { "name": "express", "version": "4.18.2" },
     "imageSettings": {
       "sizes": [
         100,
         200,
         1920
       ],
       "domains": [],
       "remotePatterns": [],
       "formats": [],
       "minimumCacheTTL": 60,
       "dangerouslyAllowSVG": false
     },
     "routes": [
       {
         "path": "/_amplify/image",
         "target": {
           "kind": "ImageOptimization",
           "cacheControl": "public, max-age=3600, immutable"
         }
       },
       {
         "path": "/*.*",
         "target": {
           "kind": "Static",
           "cacheControl": "public, max-age=2"
         },
         "fallback": {
           "kind": "Compute",
           "src": "default"
         }
       },
       {
         "path": "/*",
         "target": {
           "kind": "Compute",
           "src": "default"
         }
       }
     ],
     "computeResources": [
       {
         "name": "default",
         "runtime": "nodejs22.x",
         "entrypoint": "index.js"
       }
     ]
   }
   ```

   매니페스트는 Amplify Hosting에서 애플리케이션 배포를 처리하는 방식을 설명합니다. 기본 설정은 다음과 같습니다.
   + **version** – 사용 중인 배포 사양의 버전을 나타냅니다.
   + **framework** – 이를 조정하여 Express 서버 설정을 지정합니다.
   + **imageSettings** – 이미지 최적화를 처리하지 않는다면 이 섹션은 Express 서버에 대한 선택 사항입니다.
   + **routes** – 앱의 적합한 부분으로 트래픽을 유도하는 데 매우 중요합니다. `"kind": "Compute"` 경로에서는 트래픽이 서버 로직으로 유도됩니다.
   + **computeResources** – 이 섹션을 사용하여 Express 서버의 런타임과 진입점을 지정합니다.

다음으로, 빌드된 애플리케이션 아티팩트를 `.amplify-hosting` 배포 번들로 이동하는 빌드 후 스크립트를 설정합니다. 디렉터리 구조는 Amplify Hosting 배포 사양에 부합합니다.

**빌드 후 스크립트 설정**

1. 프로젝트 루트에 `bin`라는 디렉터리를 만듭니다.

1. `bin` 디렉터리에 `postbuild.sh`라는 파일을 만듭니다. 다음 내용을 `postbuild.sh` 파일에 추가합니다.

   ```
   #!/bin/bash
    
   rm -rf ./.amplify-hosting
    
   mkdir -p ./.amplify-hosting/compute
    
   cp -r ./dist ./.amplify-hosting/compute/default
   cp -r ./node_modules ./.amplify-hosting/compute/default/node_modules
    
   cp -r public ./.amplify-hosting/static
    
   cp deploy-manifest.json ./.amplify-hosting/deploy-manifest.json
   ```

1. `package.json` 파일에 `postbuild` 스크립트를 추가합니다. 파일이 다음과 같아야 합니다.

   ```
   "scripts": {
     "start": "ts-node src/index.ts",
     "build": "tsc",
     "serve": "node dist/index.js",
     "postbuild": "chmod +x bin/postbuild.sh && ./bin/postbuild.sh"
   }
   ```

1. 다음 명령을 실행하여 애플리케이션을 빌드합니다.

   ```
   npm run build
   ```

1. (선택 사항) Express의 경로를 조정합니다. Express 서버에 알맞게 배포 매니페스트의 경로를 수정할 수 있습니다. 예를 들어 `public` 디렉터리에 정적 자산이 없으면 Compute로 유도되는 catch-all 라우팅(`"path": "/*"`)만 필요할 수 있습니다. 이는 서버의 설정에 따라 다릅니다.

최종 디렉터리 구조는 다음과 같아야 합니다.

```
express-app/
├── .amplify-hosting/
│   ├── compute/
│   │   └── default/
│   │       ├── node_modules/
│   │       └── index.js
│   ├── static/
│   │   └── hello.txt
│   └── deploy-manifest.json
├── bin/
│   ├── .amplify-hosting/
│   │   ├── compute/
│   │   │   └── default/
│   │   └── static/
│   └── postbuild.sh*
├── dist/
│   └── index.js
├── node_modules/
├── public/
│   └── hello.txt
├── src/
│   └── index.ts
├── deploy-manifest.json
├── package.json
├── package-lock.json
└── tsconfig.json
```

**서버 배포**

1. 코드를 Git 리포지토리로 푸시한 다음에 앱을 Amplify Hosting에 배포합니다.

1. 다음과 같이 `baseDirectory`에서 `.amplify-hosting`을 가리키도록 빌드 설정을 업데이트합니다. 빌드 중에 Amplify에서는 `.amplify-hosting` 디렉터리의 매니페스트 파일을 감지하고 Express 서버를 구성된 대로 배포합니다.

   ```
   version: 1
   frontend:
     phases:
       preBuild:
         commands:
           - nvm use 18
           - npm install
       build:
         commands:
           - npm run build
     artifacts:
       baseDirectory: .amplify-hosting
       files:
         - '**/*'
   ```

1. 배포가 성공했고 서버가 올바르게 실행되는지 확인하려면 Amplify Hosting에서 제공되는 기본 URL에서 앱을 방문합니다.