我用 create-react-app 设置了我的 react 应用程序,我试图用 Docker 容器和 Docker compose 运行它。 但是,当我使用 Docker compose 运行它时出现以下错误。
web_1 | Could not find a required file.
web_1 | Name: index.html
web_1 | Searched in: /usr/src/app/web_client/public
我正在使用 Windows 10 和 Docker 快速入门终端
这是我的文件夹结构:
vocabulary-app
|
web_client
|
node_modules/
public/
src/
package.json
package-lock.json
Dockerfile
yarn.lock
docker-compose.yml
这里是docker-compose.yml
### Client SERVER ###
web:
build: ./web_client
environment:
- REACT_APP_PORT=80
expose:
- 80
ports:
- "80:80"
volumes:
- ./web_client/src:/usr/src/app/web_client/src
- ./web_client/public:/usr/src/app/web_client/public
links:
- server
command: npm start
这里是 Dockerfile
FROM node:9.0.0
RUN mkdir -p /usr/src/app/web_client
WORKDIR /usr/src/app/web_client
COPY . .
RUN rm -Rf node_modules
RUN npm install
CMD npm start
我也尝试在docker中探索文件系统,得到如下结果:
$ docker run -t -i vocabularyapp_web /bin/bash
root@2c099746ebab:/usr/src/app/web_client# ls
Dockerfile node_modules package.json src
README.md package-lock.json public yarn.lock
root@2c099746ebab:/usr/src/app/web_client# cd public/
root@2c099746ebab:/usr/src/app/web_client/public# ls
favicon.ico index.html manifest.json
这个基本上意味着 index.html
文件在那里,所以我对错误消息更加困惑。
有人对此有解决方案吗?
最佳答案
我在 Ubuntu 18.04 服务器上使用 Docker 部署 React 应用程序时遇到了同样的问题。
问题是我错过了将整个先前构建的内容复制到应用程序的工作目录 (/app
) 的步骤。
我是这样解决的:
在 RUN npm install
和 RUN npm run build
步骤之前添加以下步骤:
COPY . ./
我的 Dockerfile:
# Set base image
FROM node:latest AS builder
# Set working directory
WORKDIR /app
# Copy package.json and install packages
COPY package.json .
RUN npm install
# Copy other project files and build
COPY . ./
RUN npm run build
# Set nginx image
FROM nginx:latest
# Nginx config
RUN rm -rf /etc/nginx/conf.d/default.conf
COPY ./nginx/default.conf /etc/nginx/conf.d/default.conf
# Static build
COPY --from=builder /app/public /usr/share/nginx/html
# Set working directory
WORKDIR /usr/share/nginx/html
# Start Nginx server
CMD ["/bin/bash", "-c", "nginx -g \"daemon off;\""]
我的 docker-compose 文件:
version: "3"
services:
web:
image: my_app-frontend
build:
context: .
dockerfile: Dockerfile
environment:
REACT_APP_API_URL: ${REACT_APP_API_URL}
expose:
- "3000"
restart: always
volumes:
- .:/app
Nginx 用于提供静态文件:
创建一个名为 nginx
的目录,然后在该目录下创建一个名为 default.conf
的文件。该文件将具有以下配置:
server {
listen 80;
add_header Cache-Control no-cache;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
expires -1;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
我的 .env
创建一个 .env
文件,您将在其中存储环境变量:
REACT_APP_API_URL=https://my_api
就是这样。
我希望这会有所帮助
关于node.js - 找不到所需的文件。名称 : index. html 与 docker compose react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56927609/