hta*_*irt 5 node.js docker docker-compose
我正在学习在现实世界的开发环境中使用 Docker,因此我使用 Docker 在 Node.js 中创建了一个非常简单的“Hello World”应用程序。
包.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"
}
}
Run Code Online (Sandbox Code Playgroud)
server.js(应用程序的入口点):
var express = require('express');
express()
.get('/', function(req, res) {
res.send('Success');
})
.listen(3000, function(err) {
if (!err) { console.log('Server started') }
});
Run Code Online (Sandbox Code Playgroud)
Dockerfile.dev
FROM mhart/alpine-node:5.6.0
WORKDIR /app
ENV NODE_ENV development
EXPOSE 3000
ADD package.json /app
RUN npm install
Run Code Online (Sandbox Code Playgroud)
docker-compose.yml
version: "2"
services:
web:
build:
dockerfile: Dockerfile.dev
context: .
volumes:
- .:/app
- /app/node_modules
ports:
- 80:3000
command: node server.js
Run Code Online (Sandbox Code Playgroud)
总结一下:在package.json中,我添加了express作为依赖项,以在server.js中创建基本服务器。在Dockerfile.dev中,我定义了该环境所需的映像。请注意,我将package.json复制到工作目录中/app,然后运行npm install。最后,我使用docker-compose.yml定义我的环境。非常基本(来自许多来源以避免一些陷阱,例如添加/app/node_modulesdocker-compose 卷)
问题是运行时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
Run Code Online (Sandbox Code Playgroud)
然后重新运行相同的命令(不修改任何代码),它可以工作:
$ docker-compose up
Starting dockerrealworld_web_1
Attaching to dockerrealworld_web_1
web_1 | Server started
Run Code Online (Sandbox Code Playgroud)
为什么第一次不起作用?我做错了什么?
你几乎已经拥有了。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"]
Run Code Online (Sandbox Code Playgroud)
您已经有了编写的想法,但是 docker 镜像需要从头开始构建。
| 归档时间: |
|
| 查看次数: |
372 次 |
| 最近记录: |