即使 .env 文件存在,Docker 内的 React 应用程序也不会选择环境变量

问题描述 投票:0回答:1

我的 React 应用程序没有选择 Docker 中的环境变量。我正在使用 Fine 和 Next.js。

package.json

{
  "name": "Learning",
  "version": "0.1.0",
  "private": true,
  "engines": {
    "node": ">=18.0.0"
  },
  "scripts": {
    "dev": "cross-env NODE_OPTIONS=--max_old_space_size=4096 refine dev",
    "build": "refine build",
    "start": "refine start",
    "lint": "eslint '**/*.{js,jsx,ts,tsx}'",
    "refine": "refine"
  },
  "dependencies": {
    ...
    "next": "14.1.0",
    "react": "^18.0.0",
  },
  ...
}

文件结构:

root
|-.env
|-.env.production
|-Dockerfile
|-src
  |-app
    |-character
      |-page.tsx

page.tsx
我有:

"use client";
...
imports ...
...
const createSignalRConnection = async (userId: string) => {
    try {
      console.log(`[MainPage] Reading environment variables [${process.env.REACT_APP_BACKEND_URI}]`);
      var uri = process.env.REACT_APP_BACKEND_URI
        ? process.env.REACT_APP_BACKEND_URI
        : 'http://localhost:5244';

      uri = new URL('articlehub', uri).href;
      console.log(`[MainPage] Connecting to [${uri}]`);

我的

.env
.env.production
(都试过了,都没有用):

REACT_APP_BACKEND_URI=https://...

Dockerfile

FROM refinedev/node:18 AS base

FROM base AS deps

RUN apk add --no-cache libc6-compat

COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* .npmrc* ./

RUN \
  if [ -f yarn.lock ]; then yarn --frozen-lockfile; \
  elif [ -f package-lock.json ]; then npm ci; \
  elif [ -f pnpm-lock.yaml ]; then yarn global add pnpm && pnpm i --frozen-lockfile; \
  else echo "Lockfile not found." && exit 1; \
  fi

FROM base AS builder

COPY --from=deps /app/refine/node_modules ./node_modules

COPY . .
RUN pwd
RUN ls -la 
RUN npm run build

FROM base AS runner

ENV NODE_ENV production

COPY --from=builder /app/refine/public ./public

RUN mkdir .next
RUN chown refine:nodejs .next

COPY --from=builder --chown=refine:nodejs /app/refine/.next/standalone ./
COPY --from=builder --chown=refine:nodejs /app/refine/.next/static ./.next/static

USER refine

EXPOSE 3000

ENV PORT 3000
ENV HOSTNAME "0.0.0.0"

CMD ["node", "server.js"]

我在浏览器控制台中看到的内容:

[MainPage] Reading environment variables [undefined]
[MainPage] Connecting to [http://localhost:5244/articlehub]

我检查过,在运行

.env
之前,
npm run build
文件位于容器内。可能是什么问题?

reactjs docker next.js
1个回答
0
投票

解决方案非常简单。 变量需要加上前缀

NEXT_PUBLIC_

© www.soinside.com 2019 - 2024. All rights reserved.