Kubernetes

Dockerfile 작성시 node_modules 디렉토리를 제외하는 방법

DevOps Engineer 2024. 8. 15. 10:34
728x90

Node.js 애플리케이션을 Docker 이미지로 빌드할 때, node_modules 디렉토리를 제외하는 방법은 .dockerignore 파일을 사용하는 것입니다. 이 파일은 Docker가 컨텍스트로 전송할 파일과 디렉토리를 지정할 때 제외할 항목을 정의합니다.

 

단계 1: .dockerignore 파일 생성

프로젝트 루트 디렉토리에 .dockerignore 파일을 생성하고, node_modules 디렉토리를 제외하도록 설정합니다.

node_modules
npm-debug.log

이렇게 하면 Docker가 이미지를 빌드할 때 node_modules 디렉토리가 컨텍스트로 전송되지 않으므로, 이미지에 포함되지 않게 됩니다.

단계 2: Dockerfile 작성

Dockerfile에서 node_modules 디렉토리를 복사하지 않고, 이미지 내에서 패키지를 설치하는 방식을 사용합니다.

예) Dockerfile
# 1. Use an official Node.js runtime as a parent image
FROM node:18-alpine

# 2. Set the working directory in the container
WORKDIR /usr/src/app

# 3. Copy package.json and package-lock.json to the working directory
COPY package*.json ./

# 4. Install dependencies
RUN npm install --production

# 5. Copy the rest of the application code to the working directory
COPY . .

# 6. Expose the port the app runs on
EXPOSE 3000

# 7. Define the command to run the application
CMD [ "node", "app.js" ]

설명:

  1. .dockerignore 파일: node_modules 디렉토리와 기타 불필요한 파일을 제외하여 Docker 빌드 컨텍스트를 최적화합니다.
  2. Dockerfile: package*.json 파일만 먼저 복사하고 npm install을 실행하여 node_modules를 컨테이너 내에서 설치합니다. 이후에 애플리케이션 코드를 복사합니다.

이 방법을 사용하면 로컬 node_modules가 Docker 이미지에 포함되지 않으며, 컨테이너 내에서 필요한 의존성만 설치하게 됩니다.

728x90