# 基础镜像
FROM node:20-alpine as base
# 更改 apk 镜像源为阿里云
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories
# 设置 npm 镜像源
RUN yarn config set registry https://registry.npmmirror.com

# 全局安装 pnpm 并设置其镜像源
RUN yarn global add pnpm && pnpm config set registry https://registry.npmmirror.com

# 设置工作目录
WORKDIR /app

# 复制 pnpm workspace 配置文件
COPY pnpm-workspace.yaml ./

# 首先复制 package.json, package-lock.json 和 pnpm-lock.yaml 文件
COPY package*.json pnpm-lock.yaml* ./

COPY tsconfig.json .
# 利用 Docker 缓存机制，如果依赖没有改变则不会重新执行 pnpm install
#100-500   5-40

FROM base As server-build
WORKDIR /app
COPY packages/common /app/packages/common
COPY apps/server /app/apps/server
RUN pnpm install --filter server
RUN pnpm install --filter common
RUN pnpm --filter common generate && pnpm --filter common build:cjs
RUN pnpm --filter server build

FROM base As server-prod-dep
WORKDIR /app
COPY packages/common /app/packages/common
COPY apps/server /app/apps/server
RUN pnpm install --filter common --prod
RUN pnpm install --filter server --prod



FROM server-prod-dep as server
WORKDIR /app
ENV NODE_ENV production
COPY --from=server-build /app/packages/common/dist ./packages/common/dist
COPY --from=server-build /app/apps/server/dist ./apps/server/dist
COPY apps/server/entrypoint.sh ./apps/server/entrypoint.sh

RUN chmod +x ./apps/server/entrypoint.sh
RUN apk add --no-cache postgresql-client


EXPOSE 3000

ENTRYPOINT [ "/app/apps/server/entrypoint.sh" ]



FROM base AS web-build
# 复制其余文件到工作目录
COPY . .
RUN pnpm install
RUN pnpm --filter web build

# 第二阶段，使用 nginx 提供服务
FROM nginx:stable-alpine as web
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories
# 设置工作目录
WORKDIR /usr/share/nginx/html
# 设置环境变量
ENV NODE_ENV production
# 将构建的文件从上一阶段复制到当前镜像中
COPY --from=web-build /app/apps/web/dist .
# 删除默认的nginx配置文件并添加自定义配置
RUN rm /etc/nginx/conf.d/default.conf
COPY config/nginx/nginx.conf /etc/nginx/conf.d
# 添加 entrypoint 脚本，并确保其可执行
COPY config/nginx/entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
# 安装 envsubst 以支持环境变量替换
RUN apk add --no-cache gettext
# 暴露 80 端口
EXPOSE 80

CMD ["/usr/bin/entrypoint.sh"]


# 使用 Nginx 的 Alpine 版本作为基础镜像
FROM nginx:stable-alpine as nginx

# 替换 Alpine 的软件源为阿里云镜像
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories

# 设置工作目录
WORKDIR /usr/share/nginx/html

# 设置环境变量
ENV NODE_ENV production

# 安装 envsubst 和 inotify-tools
RUN apk add --no-cache gettext inotify-tools

# 创建 /data/uploads 目录
RUN mkdir -p /data/uploads

# 暴露 80 端口
EXPOSE 80