Dockerfile
我们的 Dockerfile
使用多阶段构建过程来创建优化的镜像。
FROM node:22.13.0-alpine AS build
WORKDIR /app
COPY pnpm-lock.yaml package.json ./
# Enable corepack for pnpm support
RUN corepack enable
RUN pnpm install --frozen-lockfile --prod
COPY . .
RUN pnpm run build
FROM node:22.13.0-alpine AS final
WORKDIR /app
COPY --from=build /app/.output .output
EXPOSE 3000
CMD ["node", ".output/server/index.mjs"]
提醒
- 使用
alpine
可以使用最小镜像,可以大幅减少构建后镜像的大小 corepack enable
跨环境一致的管理 pnpm 版本- 多阶段构建可以把最终镜像减少 90%
--from=build
确保依赖版本完全匹配- 仅复制
.output
目录可以防止源代码包含在镜像中
Docker compose 配置
services:
nuxt-app:
build:
context: .
dockerfile: Dockerfile
container_name: nuxt-app
restart: always
ports:
- '3000:3000'
healthcheck:
test: [CMD, curl, -f, 'http://localhost:3000/api/hello']
interval: 30s
timeout: 10s
deploy:
resources:
limits:
memory: 1G
提醒
- restart:始终确保应用在崩溃后重启
- healthcheck:这项配置会验证程序是否真正运行
- resources:防止容器内存泄露
- ports:端口映射允许外部直接访问
健康检查可确保您的应用程序正确响应。如果要添加自定义运行状况端点,请在 Nuxt 应用程序中创建 API 路由:
export default defineEventHandler(() => {
return "It's working now!!"
})
使用 GitHub Actions 自动构建
这个 GitHub Action 会在创建标签或者手动出发时构建和推送镜像
这段代码来自 From Local to Production: Deploy the Latest Nuxt Stack with Docker
name: Build and Push Portfolio Docker Image
on:
push:
tags:
- 'v*'
workflow_dispatch:
inputs:
tag:
description: 'Version tag (ex: v1.0.0)'
required: true
type: string
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
jobs:
build-and-push:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata for Docker
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=ref,event=tag
type=raw,value=${{ inputs.tag }},enable=${{ github.event_name == 'workflow_dispatch' }}
type=raw,value=latest,enable={{is_default_branch}}
- name: Build and push Docker image
uses: docker/build-push-action@v6
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
特性说明
- 在 git tag (v1.0.0|v1.2.0|v2.0.0)上触发
- 支持带有自定义版本标签的手动触发器
- 使用 GitHub 的缓存来加速构建
- 自动使用版本和最新标签来标记镜像
- 使用代码仓库的名称作为镜像名称
如果需要使用此设置:
- 在 GitHub 仓库中发布带有版本标签的新版本或者推送新标签
- 从 GitHub 的操作选项卡中手动出发工作流程
正确使用原则
- 在生产中之后总使用特定的版本标签
- 设置健康检查的监控
- 配置正确的日志记录
- 使用环境变量进行配置
- 设置 SSL/TLS
评论区
评论加载中...