使用 Docker 部署 Node

此 Dockerfile 用于为我们的 Qwik Node.js 应用程序构建 Docker 镜像。您可以根据需要进行编辑以使用 npm、pnpm 或 bun,方法是替换 yarn 命令和 yarn.lock 文件。

我们使用官方的 Node.js Alpine 镜像,Node 版本设置为 18.18.2(长期支持版本)。您可以根据需要选择其他版本。

然后,我们继续安装依赖项,利用 Docker 缓存机制,通过利用 package.jsonyarn.lock 的绑定挂载来避免不必要的依赖项重新安装。

安装完依赖项后,我们继续构建,设置 NODE_ENV 和 ORIGIN 环境变量。

最后,我们指定默认命令以使用 yarn serve 运行我们的 Qwik 应用程序,公开端口 3000:请注意,端口号应与您在入口适配器中选择的端口号匹配(例如:src/entry.express.tsx)。

ARG NODE_VERSION=18.18.2
 
################################################################################
# Use node image for base image for all stages.
FROM node:${NODE_VERSION}-alpine as base
 
# Set working directory for all build stages.
WORKDIR /usr/src/app
 
################################################################################
# Create a stage for installing production dependencies.
FROM base as deps
 
# Download dependencies as a separate step to take advantage of Docker's caching.
# Leverage a cache mount to /root/.yarn to speed up subsequent builds.
# Leverage bind mounts to package.json and yarn.lock to avoid having to copy them
# into this layer.
RUN --mount=type=bind,source=package.json,target=package.json \
   --mount=type=bind,source=yarn.lock,target=yarn.lock \
   --mount=type=cache,target=/root/.yarn \
   yarn install --frozen-lockfile
 
################################################################################
# Create a stage for building the application.
FROM deps as build
 
# Copy the rest of the source files into the image.
COPY . .
 
# Run the build script.
RUN yarn run build
 
################################################################################
# Create a new stage to run the application with minimal runtime dependencies
# where the necessary files are copied from the build stage.
FROM base as final
 
# Use production node environment by default.
ENV NODE_ENV production
ENV ORIGIN https://example.com
 
# Run the application as a non-root user.
USER node
 
# Copy package.json so that package manager commands can be used.
COPY package.json .
 
# Copy the production dependencies from the deps stage and also
# the built application from the build stage into the image.
COPY --from=deps /usr/src/app/node_modules ./node_modules
COPY --from=build /usr/src/app/dist ./dist
COPY --from=build /usr/src/app/server ./server
 
# Expose the port that the application listens on.
EXPOSE 3000
 
# Run the application.
CMD yarn serve

您现在可以构建您的 Docker 镜像

docker build -t your-image .

并启动 Docker 容器

docker run -dp 127.0.0.1:3000:3000 your-image

贡献者

感谢所有帮助改进此文档的贡献者!

  • nelsonprsousa
  • aendel