-
Dockerfile 작성시 node_modules 디렉토리를 제외하는 방법Kubernetes 2024. 8. 15. 10:34728x90
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" ]설명:
- .dockerignore 파일: node_modules 디렉토리와 기타 불필요한 파일을 제외하여 Docker 빌드 컨텍스트를 최적화합니다.
- Dockerfile: package*.json 파일만 먼저 복사하고 npm install을 실행하여 node_modules를 컨테이너 내에서 설치합니다. 이후에 애플리케이션 코드를 복사합니다.
이 방법을 사용하면 로컬 node_modules가 Docker 이미지에 포함되지 않으며, 컨테이너 내에서 필요한 의존성만 설치하게 됩니다.
728x90'Kubernetes' 카테고리의 다른 글
Kubernetes의 Informer와 Watcher 차이점 (0) 2025.03.02 Kubernetes에서 Controller와 Operator의 차이 (0) 2025.03.02 Kubernetes Operator Pattern: 클러스터 운영 자동화 (0) 2025.03.02 K8S API 서버의 gRPC 지원? (0) 2025.03.02 Mac OS에서 Linux 환경에 구동 가능한 컨테이너 이미지 만들기 (0) 2024.08.15