.gitignore
: node_modules
추가
$ npx gts init
package.json
- devDependencies
버전 확인package.json
- devDependencies
를 설치된 것과 비교해보며 수정하기// 아래와 같이 수정함
"devDependencies": {
"@types/node": "^16.0.0",
"gts": "^4.0.0",
"typescript": "^4.7.0"
}
scripts
추가"scripts": {
...
"start": "node build/src/index.js", // 수정
},
How it works
lint
: Lints and checks for formatting problems.fix
: Automatically fixes formatting and linting problems (if possible).clean
: Removes output files.compile
: Compiles the source code using TypeScript compiler.pretest
,posttest
andprepare
: convenience integrations.
prepare
는 이후에 Docker build를 할 때 에러가 발생하므로 삭제하는 것을 추천
package-lock.json
삭제 후 npm install
로 재설치index.js
삭제src/index.ts
에 index.js
내용 적용# 타입스크립트를 적용했으므로 @types/express 설치
$ npm i --save-dev @types/express
tsconfig.json
- "compilerOptions"
: "esModuleInterop": true
추가npm run compile
, npm run server
하면 이 전과 동일하게 "Hello World"가 보이지만 타입스크립트로 변경되어 사용되고 있다!참고 링크
FROM
: 베이스 이미지 지정RUN
: 명령 실행CMD
: 컨테이너 실행 명령COPY
: 파일 복사WORKDIR
: 작업 디렉토리FROM node:18-slim
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . ./
RUN npm run compile
RUN rm -rf ./src
CMD [ "npm", "start" ]
참고 링크
Google에서 도메인을 구입하지 않는 한 도메인을 사용하려면 도메인 소유권을 확인해야 합니다.
- 소유권 확인을 위해 웹마스터에서 속성 추가하기
- 도메인 구매 사이트에서 해당 도메인에 DNS TXT 레코드를 추가
- namecheap 기준 DNS TXT 레코드를 추가 방법
⇒ Account
⇒ Domain List
⇒ Advanced DNS
⇒ Add New Record
⇒ Host:@
/ Value:DNS TXT 레코드
를 추가
$ npm install body-parser
$ npm install @types/body-parser --save-dev
// src/index.ts
import bodyParser from 'body-parser';
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
참고 링크
$ npm install nodemon --save-dev
package.json
"scripts"에 명령어 추가"scripts": {
...
"dev": "nodemon src/index.ts"
}
$ npm install ts-node --save-dev
참고 링크
$ npm install morgan
$ npm install @types/morgan --save-dev
// src/index.ts
import morgan from 'morgan';
app.use(morgan('combined'));
format
, options
)format
, options
을 사용하여 생성format
: 미리 정의된 형식을 제공combined
: 표준 Apache combined 로그 출력:remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"
common
: 표준 Apache common 로그 출력:remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length]
dev
: 개발을 위해 Response staaus에 따라 색이 다른 축약된 로그 출력:method :url :status :response-time ms - :res[content-length]
short
: 기본값보다 짧은 로그 출력(응답 시간 포함):remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms
tiny
: 최소한의 로그 출력:method :url :status :res[content-length] - :response-time ms
참고 링크
$ npm install firebase-admin --save
import { initializeApp } from 'firebase-admin/app';
SDK 초기화
비공개 키 파일 생성
서비스 계정의 비공개 키 파일을 생성하려면 다음 안내를 따르세요.
- Firebase Console에서 설정 > 서비스 계정을 엽니다.
- 새 비공개 키 생성을 클릭한 다음 키 생성을 클릭하여 확인합니다.
- 키가 들어 있는 JSON 파일을 안전하게 저장합니다.
환경변수 설정
GOOGLEAPPLICATIONCREDENTIALS 환경 변수를 서비스 계정 키가 포함된 JSON 파일의 파일 경로로 설정합니다. 이 변수는 현재 셸 세션에만 적용되므로 새 세션을 열면 변수를 다시 설정합니다.
export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"
pwd
로 현재 경로 확인 ⇒ 현재 경로에 파일명 추가하여 환경변수 설정
import {initializeApp} from 'firebase-admin/app';
initializeApp();
// 초기화가 정상적으로 되었는지 확인하기 위해 아래와 같이 코드 수정 후 다시 원상복귀
const firebaseApp = initializeApp();
console.log(firebaseApp);
- Install Docker on your machine
- Clone the with-docker example
- Build your container:
docker build -t nextjs-docker .
- Run your container:
docker run -p 3000:3000 nextjs-docker
npx create-next-app --example with-docker nextjs-docker
# or
yarn create next-app --example with-docker nextjs-docker
# or
pnpm create next-app --example with-docker nextjs-docker
- Install the Google Cloud SDK so you can use gcloud on the command line.
- Run
gcloud auth login
to log in to your account.- Create a new project in Google Cloud Run (e.g.
nextjs-docker
). Ensure billing is turned on.- Build your container image using Cloud Build:
gcloud builds submit --tag gcr.io/PROJECT-ID/helloworld --project PROJECT-ID
. This will also enable Cloud Build for your project.- Deploy to Cloud Run:
gcloud run deploy --image gcr.io/PROJECT-ID/helloworld --project PROJECT-ID --platform managed
. Choose a region of your choice.
- Next.js 예제의 package.json에 scripts 추가
"scripts": { ... "gcloud:build": "gcloud builds submit --tag gcr.io/PROJECT-ID/helloworld --project PROJECT-ID", "gcloud:deploy": "gcloud run deploy --image gcr.io/PROJECT-ID/helloworld --project PROJECT-ID --platform managed" },
주의사항
COPY package.json yarn.lock ./
- Next.js 예제를 생성하면 기본적으로 생성된 Dockerfile에서
yarn
을 가져가는 코드가 있다.
⇒yarn
을 이용하세요..gitignore
에yarn.lock
이 포함되어 있어 Cloud Build를 할 때 에러가 발생
⇒.gitignore
에서yarn.lock
제거