我需要运行两次docker-compose才没有错误
我正在学习在真实世界的开发环境中使用Docker,所以我使用Docker在Node.js中创build了一个非常简单的“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中创build一个基本的服务器。 在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的图像从头开始build设。