我正在使用以下命令将我的 React on Node.js 应用程序部署到云运行
gcloud builds submit --tag gcr.io/projectname/myapp-ui
gcloud run deploy myapp--image gcr.io/projectname/myapp-ui --platform managed --region asia-southeast1
它is部署得很好,但它没有从
build\
目录部署缩小的JS
src\
的源代码以及所有原始 .js 文件。
如何强制 gcloud 部署构建目录(我已验证
build\
目录确实具有构建的、缩小的 js 代码)?
这是我的dockerfile
# build environment
FROM node:18-alpine as react-build
WORKDIR /app
COPY . ./
RUN yarn
RUN yarn build
# server environment
FROM nginx:alpine
COPY nginx.conf /etc/nginx/conf.d/configfile.template
ENV PORT 8080
ENV HOST 0.0.0.0
RUN sh -c "envsubst '\$PORT' < /etc/nginx/conf.d/configfile.template > /etc/nginx/conf.d/default.conf"
COPY --from=react-build /app/build /usr/share/nginx/html
EXPOSE 8080
CMD ["nginx", "-g", "daemon off;"]
我的package.json
{
"name": "myapp",
"version": "0.1.0",
"private": true,
"dependencies": {
"@emotion/react": "^11.11.0",
"@emotion/styled": "^11.11.0",
"@material-ui/core": "^4.12.4",
"@mui/icons-material": "^5.11.16",
"@mui/material": "^5.13.3",
"@testing-library/jest-dom": "^5.14.1",
"@testing-library/react": "^11.2.7",
"@testing-library/user-event": "^12.8.3",
"axios": "^1.4.0",
"firebase": "^10.0.0",
"lightweight-charts": "^4.0.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-gtm-module": "^2.0.11",
"react-router-dom": "^5.2.0",
"react-scripts": "^5.0.1",
"react-spring": "^9.7.1",
"styled-components": "^5.3.11"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
您的 Dockerfile 当前将构建目录的内容复制到 nginx 映像中。但是,没有相应地设置工作目录。因此,当 nginx 执行时,它仍然会在 src 目录中搜索文件。
要解决此问题,您可以尝试修改 Dockerfile 中的
COPY
命令,如下所示:
WORKDIR /usr/share/nginx/html # Define the working directory
COPY --from=react-build /app/build . # Transfer the build files into the designated working directory
通过实施此更改,构建目录将被复制到 nginx 映像中,并建立指定的工作目录。
成功执行这些修改后,您可以继续重新部署您的应用程序。因此,您的应用程序将正确利用位于构建目录中的缩小的 JS 文件。
详细步骤:
COPY --from=react-build /app/build /usr/share/nginx/html:WORKDIR
再次重建您的 Docker 镜像。
启动将应用程序部署到 Cloud Run。