add docker support

This commit is contained in:
xd
2025-07-28 16:38:37 +08:00
parent 403bd27f95
commit 87ed1833bb
42 changed files with 168 additions and 900 deletions

53
.docker/Dockerfile Normal file
View File

@ -0,0 +1,53 @@
# 构建阶段使用 Node 镜像
FROM node:22-alpine as builder
# 设置工作目录
WORKDIR /app
# 设置阿里云镜像源
RUN yarn config set registry https://registry.npmmirror.com/ && \
npm config set registry https://registry.npmmirror.com/
# 复制 package.json 和 yarn.lock
COPY package.json yarn.lock ./
# 安装依赖
RUN yarn
# 复制源代码
COPY . .
# 构建项目
RUN yarn build
# 使用轻量级的 Node 镜像作为基础镜像
FROM node:22-alpine
# 设置工作目录
WORKDIR /app
# 设置阿里云镜像源
RUN yarn config set registry https://registry.npmmirror.com/ && \
npm config set registry https://registry.npmmirror.com/
# 安装简单的静态文件服务器
RUN yarn global add serve
# 将构建产物复制到工作目录
COPY --from=builder /app/dist ./dist
# 复制环境变量注入脚本
COPY .docker/env.sh ./env.sh
RUN chmod +x ./env.sh
# 暴露服务端口
EXPOSE 5000
# 设置环境变量
ENV PORT=5000
ENV NODE_ENV=production
ARG BASE_URL
ENV BASE_URL=${BASE_URL}
# 启动命令:先执行环境变量注入脚本,再启动静态服务器
CMD ["/bin/sh", "-c", "./env.sh && serve -s dist"]

29
.docker/build.sh Normal file
View File

@ -0,0 +1,29 @@
#!/bin/bash
# 停止脚本在出错时执行
set -e
# 获取版本号参数,默认为 latest
VERSION=${1:-latest}
# 设置 Docker 镜像名称
IMAGE_NAME="neighbourhood-frontend"
FULL_IMAGE_NAME="${IMAGE_NAME}:${VERSION}"
# 显示构建信息
echo "正在构建 Docker 镜像: ${FULL_IMAGE_NAME}"
echo "使用阿里云镜像源加速构建"
# 切换到项目根目录
cd "$(dirname "$0")/.." || exit 1
# 构建 Docker 镜像
docker build -t ${FULL_IMAGE_NAME} -f .docker/Dockerfile .
echo "镜像构建完成: ${FULL_IMAGE_NAME}"
# 运行示例
echo "运行示例:"
echo "docker run -d -p 5000:5000 -e BASE_URL=https://api.example.com ${FULL_IMAGE_NAME}"
echo "构建脚本执行完毕!"

22
.docker/env.sh Normal file
View File

@ -0,0 +1,22 @@
#!/bin/sh
# 生成环境变量配置文件
echo "window.ENV = {" > ./dist/env-config.js
# 注入 BASE_URL 环境变量
if [ -n "$BASE_URL" ]; then
echo " BASE_URL: '$BASE_URL'," >> ./dist/env-config.js
fi
# 添加其他环境变量,如有需要
# if [ -n "$API_KEY" ]; then
# echo " API_KEY: '$API_KEY'," >> ./dist/env-config.js
# fi
# 关闭对象
echo "};" >> ./dist/env-config.js
# 确保 env-config.js 被引入到 index.html
sed -i "s/<\/head>/\n<script src=\"\/env-config.js\"><\/script>\n<\/head>/g" ./dist/index.html
echo "环境变量已注入到 dist/env-config.js 并已在 index.html 中引入"