![](/img/trans.png)
[英]Why is it that when I install a new npm package I have to run “docker-compose down” followed by “docker-compose up --build”?
[英]I need to run twice docker-compose to not have errors
我正在學習在現實世界開發環境中使用Docker,所以我使用Docker在Node.js中創建了一個非常簡單的“Hello World”應用程序。
的package.json
{
"name": "docker-real-world",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.14.0"
}
}
server.js (應用程序的入口點):
var express = require('express');
express()
.get('/', function(req, res) {
res.send('Success');
})
.listen(3000, function(err) {
if (!err) { console.log('Server started') }
});
Dockerfile.dev
FROM mhart/alpine-node:5.6.0
WORKDIR /app
ENV NODE_ENV development
EXPOSE 3000
ADD package.json /app
RUN npm install
泊塢窗,compose.yml
version: "2"
services:
web:
build:
dockerfile: Dockerfile.dev
context: .
volumes:
- .:/app
- /app/node_modules
ports:
- 80:3000
command: node server.js
總結一下:在package.json中,我將express作為依賴項添加到server.js中創建基本服務器。 在Dockerfile.dev中,我定義了此環境所需的圖像。 請注意,我在/app
工作目錄中復制了package.json ,然后運行npm install
。 最后,我使用docker-compose.yml定義我的環境。 非常基礎(從許多來源避免一些陷阱,比如在/app/node_modules
-compose卷中添加/app/node_modules
)
問題是運行docker-compose up
會產生以下錯誤:
$ docker-compose up
Building web
Step 1 : FROM mhart/alpine-node:5.6.0
---> cdbaa8672a25
...
...
web_1 | module.js:341
web_1 | throw err;
web_1 | ^
web_1 |
web_1 | Error: Cannot find module 'express'
web_1 | at Function.Module._resolveFilename (module.js:339:15)
web_1 | at Function.Module._load (module.js:290:25)
web_1 | at Module.require (module.js:367:17)
web_1 | at require (internal/module.js:16:19)
web_1 | at Object.<anonymous> (/app/server.js:1:77)
web_1 | at Module._compile (module.js:413:34)
web_1 | at Object.Module._extensions..js (module.js:422:10)
web_1 | at Module.load (module.js:357:32)
web_1 | at Function.Module._load (module.js:314:12)
web_1 | at Function.Module.runMain (module.js:447:10)
dockerrealworld_web_1 exited with code 1
然后重新運行相同的命令(不修改任何代碼),它的工作原理:
$ docker-compose up
Starting dockerrealworld_web_1
Attaching to dockerrealworld_web_1
web_1 | Server started
為什么它第一次不起作用? 我做錯了什么?
你幾乎擁有它。 Dockerfile需要......
# Create the location of our app within the image
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
# Copy the package json containing dependencies, then install
COPY package.json /usr/src/app/
RUN npm install
# Copy the current source to the image
COPY . /usr/src/app
# Start the service
ENTRYPOINT ["npm", "start"]
你有寫作的想法,但是docker圖像需要從頭開始構建。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.