一直想写一个关于多容器开发环境,以后会逐步更新,今天先从简单的hello world开始吧
下面的例子来自于
https://nodejs.org/zh-cn/docs/guides/nodejs-docker-webapp/
一共4个文件,分别是
dockerfile
docker-compose.yml
package.json
server.js
# dockerfile以下
FROM node:12
# Create app directory
WORKDIR /usr/src/app
# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./
RUN npm install
# If you are building your code for production
# RUN npm ci --only=production
# Bundle app source
COPY . .
EXPOSE 3000
CMD [ "node", "server.js" ]
# package.json
{
"name": "docker_web_app",
"version": "1.0.0",
"description": "Node.js on Docker",
"author": "First Last <[email protected]>",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"express": "^4.16.1"
}
}
# server.js
'use strict';
const express = require('express');
// Constants
const PORT = 3000;
const HOST = '0.0.0.0';
// App
const app = express();
app.get('/', (req, res) => {
res.send('Hello World');
});
app.listen(PORT, HOST, () => {
console.log(`Running on http://${HOST}:${PORT}`);
});
# docker-compose.yml
version: '3.0'
services:
node-web:
build: ./
ports:
- "3000:3000"
volumes:
- ./:/usr/src/app
- /usr/src/app/node_modules
command: npm start
注意哦!!!第10行 volumes里必须要把container中的node_modules映射出来,否则会报错
internal/modules/cjs/loader.js:818
code: 'MODULE_NOT_FOUND',
requireStack: [ '/usr/src/app/server.js' ]
这是因为宿主机目录中没有node_modules而引起的莫名错误。。。
普通的目录结构
👇
docker-compose up
运行成功!😃,打开浏览器访问
localhost:3000
总结:
非常简单方便的docker容器化部署nodejs,过去自己下载自己配置,弄半天的情景不复存在!这是简单实用基础版本,拥抱docker吧!
版权归原作者 家用通马桶高级工程师 所有, 如有侵权,请联系我们删除。