Docker を使用した Node.js でのデプロイ
この Dockerfile は、Qwik Node.js アプリケーションの Docker イメージをビルドするために使用されます。 yarn コマンドと `yarn.lock` ファイルを置き換えることで、npm、pnpm、または bun を使用するように適宜編集できます。
Node バージョンを 18.18.2(長期サポートバージョン)に設定した公式の Node.js Alpine イメージを使用しています。必要に応じて他のバージョンを選択することもできます。
次に、依存関係をインストールします。`package.json` と `yarn.lock` のバインドマウントを利用することで、Docker のキャッシュメカニズムを活用し、依存関係の不要な再インストールを回避します。
依存関係がインストールされたら、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