考虑:
# Use an official node image as the base image
FROM node:16
# Set the working directory in the container
WORKDIR /app
# Copy the package.json and package-lock.json files
COPY package*.json ./
# Install the dependencies
RUN npm install
# Copy the rest of the application code
COPY . .
# Build the React app for production
RUN npm run build
# Install a simple HTTP server to serve static files
RUN npm install -g serve
# Set the command to run the HTTP server on the production build
CMD ["serve", "-s", "build"]
# Expose port 3000
EXPOSE 3000
为什么我们可以使用 Node.js 镜像来 dockerize React 应用程序?它应该用于运行 Node.js 应用程序。还要在容器的命令提示符中写入,我们使用 cmd。那么为什么我们使用 run npm install 来安装依赖项呢?应该需要 cmd npm install。
为什么我们可以使用node镜像来dockerize React应用程序?它应该用于运行节点应用程序。
从技术上讲,静态 React 应用程序可以由任何能够通过 HTTP 托管静态内容的容器提供服务;你可以使用例如Python 的
http.server
、Caddy、Nginx 或任何为其提供服务的东西。
要构建静态页面以从源提供服务,您通常需要 Node,因此为了使用其他东西进行运行时服务,您需要一个多阶段构建。这里所做的事情更加简单。
那么为什么我们使用 run npm install 来安装依赖项呢?应该需要 cmd npm install。
CMD
设置当您运行 Dockerfile 构建的映像时容器默认运行的命令。
RUN
步骤在您构建映像时在您的计算机(或构建计算机)上运行,而不是在运行时运行。