【发布时间】:2019-02-27 05:07:42
【问题描述】:
我正在尝试为我的示例项目运行 docker,在容器中我需要一个端口来运行,但是反应代码的构建将用作 index.html,我有以下文件夹结构。
在 index.js 文件中我尝试添加静态路径,我在这里做错了什么?我已经评论过了。。
我已经尝试了很多。
sampleapp
client
// using cra (create react app) files
src
public
...
server
index.js
Dockerfile
// app.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
state = {
response: null
}
componentWillMount(){
this.dataFetching()
}
dataFetching = async () => {
const resjson = await fetch('/api/data');
const res = await resjson.json();
this.setState({
response: res.data
})
}
render() {
return (
this.state.response ? this.state.response : null
);
}
}
export default App;
// package.json --client
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.8.3",
"react-dom": "^16.8.3",
"react-scripts": "2.1.5"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
],
"proxy": "http://localhost:4000"
}
// index.js -- 服务器
const express = require('express');
const path = require('path');
const app = express();
// app.use(express.static(path.join(__dirname, 'build')));
// app.get('/*', function(req, res) {
// res.sendFile(path.join(__dirname, '..', 'app', 'build', 'index.html'));
// });
app.get('/api/data', (req, res) => {
res.send({data: "Success"})
})
app.listen(4000);
// Dockerfile - 示例应用程序
FROM node:10.15.1-alpine
COPY . /var/app
WORKDIR /var/app/client
RUN npm install --no-cache && npm run build && npm install -g serve
WORKDIR /var/app/server
RUN npm install --no-cache
EXPOSE 4000
EXPOSE 3000
【问题讨论】:
-
为什么要使用两个
EXPOSE?最好改用Isomorphic。 -
怎么做
-
我可以在没有 docker 的情况下运行应用程序,但是使用 docker 时无法按预期工作。
-
你需要添加
CMD以便容器可以使用它来启动 -
对于
EXPOSE,您可以将其更改为EXPOSE 3000 4000