我有一个包含NodeJS服务器和ReactJS客户端的应用程序。该项目的结构如下:
client
Dockerfile
package.json
.
.
.
server
Dockerfile
package.json
.
.
.
docker-compose.yml
.gitignore
要同时运行这两项,我正在使用docker-compose.yml
:
version: "3"
services:
server:
build: ./server
expose:
- 8000
environment:
API_HOST: "http://localhost:3000/"
APP_SERVER_PORT: 8000
MYSQL_HOST_IP: mysql
ports:
- 8000:8000
volumes:
- ./server:/app
command: yarn start
client:
build: ./client
environment:
REACT_APP_PORT: 3000
NODE_PATH: src
expose:
- 3000
ports:
- 3000:3000
volumes:
- ./client/src:/app/src
- ./client/public:/app/public
links:
- server
command: yarn start
在client
和server
文件夹的每个文件夹中,我都有一个Dockerfile
(每个文件夹都相同):
FROM node:10-alpine
RUN mkdir -p /app
WORKDIR /app
COPY package.json /app
COPY yarn.lock /app
COPY . /app
RUN yarn install
CMD ["yarn", "start"]
EXPOSE 80
其中客户端的start
脚本只是react-scripts start
,而服务器的脚本是nodemon index.js
。客户端的package.json
具有一个代理,该代理应该允许它与服务器通信:
"proxy": "http://server:8000",
react应用将调用如下所示的组件:
import React from 'react';
import axios from 'axios';
function callServer() {
axios.get('http://localhost:8000/test', {
params: {
table: 'sample',
},
}).then((response) => {
console.log(response.data);
});
}
export function SampleComponent() {
return (
<div>
This is a sample component
{callServer()}
</div>
);
}
将根据/test
文件中的定义在节点服务器中调用index.js
路径:
const cors = require('cors');
const express = require('express');
const app = express();
app.use(cors());
app.listen(process.env.APP_SERVER_PORT, () => {
console.log(`App server now listening on port ${process.env.APP_SERVER_PORT}`);
});
app.get('/test', (req, res) => {
res.send('hi');
});
现在,当我在Linux Mint机器上运行该代码时,此代码就像一个超级按钮,但是当我在Windows 10上运行它时,出现以下错误(我都在Chrome上运行):
GET http://localhost:8000/test?table=sample net::ERR_CONNECTION_REFUSED
是否需要在其他端口或IP地址上运行它们?我在某处读到该连接可能使用的是Windows网络,而不是docker-compose
创建的网络,但我什至不知道如何开始进行诊断。如果您有什么想法可以帮助您,请告诉我。
编辑:以下是docker ps
的结果:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1824c61bbe99 react-node-mysql-docker-boilerplate_client "docker-entrypoint.s…" 3 minutes ago Up 3 minutes 80/tcp, 0.0.0.0:3000->3000/tcp react-node-mysql-docker-boilerplate_client_1
,这里是docker ps -a
。由于某种原因,服务器映像似乎一启动就自行停止
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1824c61bbe99 react-node-mysql-docker-boilerplate_client "docker-entrypoint.s…" 3 minutes ago Up 3 minutes 80/tcp, 0.0.0.0:3000->3000/tcp react-node-mysql-docker-boilerplate_client_1
5c26276e37d1 react-node-mysql-docker-boilerplate_server "docker-entrypoint.s…" 3 minutes ago Exited (127) 3 minutes ago react-node-mysql-docker-boilerplate_server_1