docker - 如何交朋友 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,同时删除源和包..
试图在短期内改写它
- 在开发模式下 backend:someport 在本地运行,前端 webserver:80 将 api 请求代理到 localhost:someport
- 如果你把后端放在容器中,什么都不会改变
- 如果您将 webserver 放在容器中 localhost:someport 将停止工作,因为没有后端:someport 在该容器内运行,显然......
- 生产前端需要构建过程,其中涉及大量临时文件
解决方案?
解决方案
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
推荐阅读
- ruby-on-rails - Souce Sans Pro 字体不适用于开发 Rails 应用程序
- node.js - 我应该什么时候关闭这个数据库连接?
- sql-server - 为什么 asp.net 核心应用程序在连接到 SQL Server 时使用与 AppPool 身份不同的用户进行 Windows 身份验证?
- android-studio - 在使用 Android Studio 启动期间失去与设备的连接
- unity3d - 停止 Unity 中每个场景中的所有 AudioSource
- solidity - 恢复 ERC20.transferFrom
- apache - Apache 为 dav_svn 启用 dump_io
- html - 为什么 display:block 会影响 Firefox 中的垂直对齐?
- javascript - 如何在不使用任何 HTTP 服务器的情况下从本地文件 url(“file:///”)访问 react-app 构建?
- javascript - 难以创建 Jquery 循环以反复更改背景颜色和动画元素