一直想写一个关于多容器开发环境,以后会逐步更新,今天先从简单的hello world开始吧
下面的例子来自于 https://nodejs.org/zh-cn/docs/guides/nodejs-docker-webapp/
一共4个文件,分别是
dockerfile
docker-compose.yml
package.json文章来源:https://www.toymoban.com/news/detail-417292.html
server.js文章来源地址https://www.toymoban.com/news/detail-417292.html
# 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 <first.last@example.com>",
"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吧!
到了这里,关于docker部署nodejs开发环境,基础示例篇的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!