容器化一个简单的 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 发布端口号,因为前端代码不在容器中执行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值