栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

容器化一个简单的 Mern stack app

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

容器化一个简单的 Mern stack app

前端由 React 组成, 后端由 Node 和 MongoDB 组成。

1. 创建 docker 网络:
docker network create goals-net
2. 创建 MongoDB 容器
docker run --name mongodb -d --rm --network goals-net mongo
3. 创建 Node 容器 3.1 创建image:
docker build -t goals-node . 
3.2 创建容器:
docker run --rm -d -p 80:80 --network goals-net goals-node
4. 创建 React 容器: 4.1 创建 image:
 docker build -t goals-react . 
4.2 创建容器:
docker run --name react-frontend -it --rm -d -p 3000:3000 goals-react
5. 代码中和 ip 有关的设置: 5.1 后端连 MongoDB 部分的代码:

这里 mongodb 是运行MongoDB的容器的名称。

mongoose.connect(
  'mongodb://mongodb:27017/course-goals',
  (err) => {
    } else {
      app.listen(80);
    }
  }
);
5.2 react 与 node 通信的代码不需要修改

例如下面的代码段,localhost 不能改成 goals-backend,依然保持为 localhost, 原因是对于 react, 只有使用 npm start 启动的开发服务器在容器中运行,其他代码在浏览器中运行。

useEffect(function () {
    async function fetchData() {
      setIsLoading(true);
      try {
        const response = await fetch("http://localhost/goals");
        const resData = await response.json();
        if (!response.ok) {
          throw new Error(resData.message || "Fetching the goals failed.");
        }

        setLoadedGoals(resData.goals);
      } catch (err) {
        setError(
          err.message ||
            "Fetching goals failed - the server responsed with an error."
        );
      }
      setIsLoading(false);
    }
    fetchData();
  }, []);

因为 react 代码在浏览器中运行,不在容器中运行,因此不需要指定 --network 选项,因为用不到。

后端 node 需要使用 --publish 发布端口号,因为前端代码不在容器中执行。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/841328.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号