» Node.js:使用Kafka构建事件驱动微服务 » 5. 部署 » 5.1 Dockerfile

Dockerfile

Docker 允许开发人员将他们的应用程序以及所有依赖项打包成一个称为容器的单个单元。这确保了在不同环境(如开发、测试和生产)之间的一致性,减少了“但是它在我的机器上运行正常”的问题。

安装 Docker: https://docs.docker.com/engine/install/

web 服务的 Dockerfile

添加 src/web/Dockerfile:

# Use the official Node.js image with specified version
FROM node:20.11-alpine3.18

# Set the working directory inside the container
WORKDIR /usr/src/app

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

# Install project dependencies
RUN npm install

# Copy the rest of the application code to the working directory
COPY src/ /usr/src/app/src
COPY tsconfig.json ./

# Build TypeScript code
RUN npm run build

# Command to run the application
CMD ["node", "dist/web/app.js"]

添加 src/web/.dockerignore:

config.json

Alpine Linux 是一个轻量级的安全的 Linux 发行版,特别适用于容器化环境、嵌入式系统和资源受限环境。这些环境下效率和安全性至关重要。

为 web 服务构建 docker 镜像:

docker build -t lrbooks_web_node:latest -f src/web/Dockerfile .

相似地,添加另外 2 个 Dockerfiles:

热搜服务的 Dockerfile

添加 src/trend/Dockerfile:

# Use the official Node.js image with specified version
FROM node:20.11-alpine3.18

# Set the working directory inside the container
WORKDIR /usr/src/app

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

# Install project dependencies
RUN npm install

# Copy the rest of the application code to the working directory
COPY src/ /usr/src/app/src
COPY tsconfig.json ./

# Build TypeScript code
RUN npm run build

# Command to run the application
CMD ["node", "dist/trend/app.js"]

添加 src/trend/.dockerignore:

config.json

推荐服务的 Dockerfile

添加 src/recommendation/Dockerfile:

# Use the official Node.js image with specified version
FROM node:20.11-alpine3.18

# Set the working directory inside the container
WORKDIR /usr/src/app

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

# Install project dependencies
RUN npm install

# Copy the rest of the application code to the working directory
COPY src/ /usr/src/app/src
COPY tsconfig.json ./

# Build TypeScript code
RUN npm run build

# Command to run the application
CMD ["node", "dist/recommendation/app.js"]

添加 src/recommendation/.dockerignore:

config.json

准备好所有 Dockerfile 之后,就可以在 Docker Compose 里启动所有服务了。

上页下页