Next.js Dockerfile

곰튀김·2023년 8월 2일
0
post-thumbnail

Goal

Next.js 로 작성한 사이트를 Docker로 빌드해서 컨테이너를 ECS로 서비스 한다.

Reference

next.js / examples / with-docker

Steps

Standalone

  • next 앱 필요 없이 node로 직접 서버를 구동시키기 위해서 standalone 옵션으로 빌드 해야함.
  • next.config.js 에 output 옵션으로 standalone 주기
module.exports = {
  output: 'standalone',
}

Dockerfile 준비

빌드하기

FROM node:16-alpine AS base

### BUILD ###

FROM base AS builder
WORKDIR /usr/src/app
COPY . .
RUN yarn --frozen-lockfile
RUN yarn build
  • .dockerignore 에 node_modules 나 .next 같은거 넣어줘야 COPY . . 할 때 불필요한 거 안딸려 감.
  • 빌드 하고나면 .next 폴더에 실행을 위한 모든 것이 생성됨

실행하기

### RUN ###

FROM base As runner
WORKDIR /usr/src/app

ENV HOSTNAME localhost
ENV PORT 3000
ENV NODE_ENV production

COPY --from=builder $APP_PATH/public ./public
COPY --from=builder $APP_PATH/.next/standalone ./
COPY --from=builder $APP_PATH/.next/static ./.next/static

EXPOSE 3000

CMD ["node", "server.js"]
  • builder 에서 만들어진 .next/standalon 에 실행할 서버코드가 모두 들어있다.
  • public 하고 .next/static 은 따로 복사해 줘야 한다.

테스트

$ docker build -t nextjs-site .
$ docker run -p 80:3000 nextjs-site

Result

  • 빌드 잘 됨. 실행 잘 됨.
전체 Dockerfile
FROM node:16-alpine AS base

### BUILD ###

FROM base AS builder
WORKDIR /usr/src/app
COPY . .
RUN yarn --frozen-lockfile
RUN yarn build



### RUN ###

FROM base As runner
WORKDIR /usr/src/app

ENV HOSTNAME localhost
ENV PORT 3000
ENV NODE_ENV production

COPY --from=builder $APP_PATH/public ./public
COPY --from=builder $APP_PATH/.next/standalone ./
COPY --from=builder $APP_PATH/.next/static ./.next/static

EXPOSE 3000

CMD ["node", "server.js"]
profile
사실주의 프로그래머

1개의 댓글

comment-user-thumbnail
2023년 8월 2일

감사합니다. 이런 정보를 나눠주셔서 좋아요.

답글 달기