首页 > 解决方案 > 如何交朋友 react.js app、nginx 和 docker-compose?

问题描述

React 应用程序是一个客户端,因此它有一些要连接的端点(无论是 axios http 还是 websocket)

通常,类似后端的客户端(各种模块化服务器微服务)从 ENV 获取它,这是在容器构建过程中设置的,并在 docker-compose.yml 文件中声明。启动应用程序需要构建过程中的所有内容,最后一步是运行命令。

React Frontend 也需要构建过程,但从某种意义上说,您实际上在构建完成时并没有运行“bundle.js”,并且在构建后不需要所有其余部分。实际上,我在主机上构建,在 docker-compose.yml 中,我说:“nginx 映像”和“将外部配置和静态文件挂载为卷”。但是那样我不能使用端点,并且后端 api 的 nginx 代理不起作用。

我是否应该编写 Dockerfile 来构建前端,以及如何将其集成到 nginx 生成的图像中?(对于构建我需要节点映像,但对于运行我需要 nginx,同时删除源和包..


试图在短期内改写它

解决方案?

标签: dockernginxdocker-composedockerfilenginx-config

解决方案


Month later I've retirned here, and could share found solution. Best results were achieved via two-pass build procedure. Here is a simple dockerfile, illistrating this approach:

#dont use alpine if you need gyp (web3, sha3 and friends..)
FROM node:current as builder
WORKDIR /frontend

# install packages
COPY ./.yarnrc ./
COPY ./package.json ./
RUN yarn install

# build front
COPY ./.babelrc ./
COPY ./webpack.config.js ./
COPY ./pub ./pub
COPY ./src ./src
RUN yarn build

# copy result static to nginx
FROM nginx:stable-alpine
COPY --from=builder /frontend/dist/ /data/www/
COPY ./nginx /etc/nginx

PROS:

  • Everything (static, configs) is bundled inside an image
  • No need for any volumes (logs are streamed to syslog)
  • Tiny image size (around 20 megs)
  • Extremely easy to deploy - just upload image and here you go
  • No need to have node.js and friends installed on dev machine

CONS:

  • Long rebuild time if React sources were changed
  • Sometimes volumes may be convenient

推荐阅读