前端由 React 组成, 后端由 Node 和 MongoDB 组成。
1. 创建 docker 网络:docker network create goals-net2. 创建 MongoDB 容器
docker run --name mongodb -d --rm --network goals-net mongo3. 创建 Node 容器 3.1 创建image:
docker build -t goals-node .3.2 创建容器:
docker run --rm -d -p 80:80 --network goals-net goals-node4. 创建 React 容器: 4.1 创建 image:
docker build -t goals-react .4.2 创建容器:
docker run --name react-frontend -it --rm -d -p 3000:3000 goals-react5. 代码中和 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 发布端口号,因为前端代码不在容器中执行。



