【发布时间】:2021-05-15 17:24:42
【问题描述】:
我正在使用教程在线学习 Docker。唯一要求我构建的是 Dockerfile,所以我确定问题出在那儿,但我还没有找到有效的方法来调试问题。
问题是当我使用构建的 docker 映像运行容器时,index.html 在 localhost 中呈现,但 bundle.js 不呈现并在控制台中的标题中给出错误。当我在本地机器上打包 webpack 并打开 index.html 时,网页会正确呈现。
Dockerfile:
FROM node:8.15-alpine as build-stage
COPY . /app
RUN npm install && npm start
FROM nginx:1.15
EXPOSE 80
COPY --from=build-stage /app /usr/share/nginx/html
COPY --from=build-stage /app/nginx.conf /etc/nginx/conf.d/default.conf
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Todo App</title>
<link href="https://fonts.googleapis.com/css?family=Roboto+Slab" rel="stylesheet">
<link rel="stylesheet" href="./styles/main.css" >
</head>
<body>
<div id="content"></div>
<script src="./bundle.js"></script>
</body>
</html>
package.json:
{
"name": "todos",
"version": "1.0.0",
"description": "This README would normally document whatever steps are necessary to get the application up and running.",
"main": "index.js",
"directories": {
"test": "test"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack --mode=development"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@babel/core": "^7.1.2",
"@babel/preset-env": "^7.1.0",
"@babel/preset-react": "^7.0.0",
"babel-loader": "^8.2.2",
"lodash": "^4.17.4",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-redux": "^5.0.6",
"redux": "^3.7.2",
"webpack": "^4.20.2",
"webpack-cli": "^3.1.2"
},
"devDependencies": {}
}
webpack.config.js:
const path = require('path');
module.exports = {
context: __dirname,
entry: './frontend/todo_redux.jsx',
output: {
path: path.resolve(__dirname),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/env', '@babel/react']
}
},
}
]
},
devtool: 'source-map',
resolve: {
extensions: [".js", ".jsx", "*"]
}
};
nginx.conf
# This will tell our nginx server what path
# we want it to use for the html it renders
server {
# list on port 80
listen 80;
location / {
# to learn more about location blocks check out this resouce:
# https://www.linode.com/docs/web-servers/nginx/how-to-configure-nginx/#location-blocks
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html =404;
}
}
更新:删除了我在 Dockerfile 的节点构建部分中的 CMD 行,将 RUN npm install 更改为 RUN npm install && npm start,现在正在创建 bundle.js 文件并将其添加到 nginx,但同样的错误仍然存在。
【问题讨论】:
-
你在本地使用的是什么版本的 Node.js?您的 Dockerfile 引用了一个相当旧的 Node 版本,我很好奇问题是否出在您的 Dockerfile 构建容器时使用的 Node 版本中。
-
如果是目录副本,可以确定 docker config COPY 命令需要
<dest>以/结尾。 (/usr/share/nginx/html-->/usr/share/nginx/html/) -
v14.13.0 他们确实提到在教程中总是尝试使用相同的版本。 @KevinCodes
-
@RandyCasburn 有一个很好的观点。我会试一试。以下是供参考的文档:docs.docker.com/engine/reference/builder/#copy
-
@JohnO'Brien 您可以尝试进入您的 Docker 容器并查看您的 index.html 和 bundle.js 文件吗?
docker exec -it <your-container-name> sh这个命令会给你一个进入容器的交互式终端,然后从那里使用cat命令。我们正在检查文件是否看起来像是在容器构建期间被适当复制的。
标签: javascript node.js docker nginx webpack