1. 在 /home 下,先賦予當前用戶讀寫權限,chmod 777 ./nodejs/ ,而後新建/nodejs/demo1文件夾和 /nodejs/Dockerfile文件,node
/nodejs/demo1文件夾 用來放項目源碼docker
/nodejs/Dockerfile文件自動化跑腳本npm
2.demo1文件夾下,有server.js、package.jsonjson
// server.js const Koa = require('koa'); const app = new Koa(); app.use(async ctx => { ctx.body = 'Hello docker'; }); app.listen(8081);
package.json瀏覽器
{ "name": "demo1", "version": "1.0.0", "private": true, "scripts": { "start": "node server.js" }, "dependencies": { "koa": "^2.5.0" } }
3. Dockerfilebash
FROM node:8.9-alpine # 做者 MAINTAINER fengnovo # 執行命令,建立文件夾 RUN mkdir -p /home/nodejs/demoProject1 # 將demoProject1目錄拷貝到鏡像裏 ADD ./demo1 /home/nodejs/demoProject1 # 指定工做目錄 WORKDIR /home/nodejs/demoProject1 # 安裝依賴及構建node應用 RUN npm install # RUN npm build # 配置系統變量,指定端口 ENV HOST 0.0.0.0 ENV PORT 8081 #對外暴露的端口 EXPOSE 3000 #程序啓動腳本 CMD ["npm", "start"]
4.在nodejs目錄下運行app
docker build -t demo1 .koa
5. 完了,再運行curl
docker imagesasync
能夠看到
REPOSITORY TAG IMAGE ID CREATED SIZE
demo1 latest 9ec9bfe046e8 About a minute ago 69.5MB
6.完了,再運行,下面是將8081映射到8080端口
docker run -d -p 8080:8081 demo1
能夠看到
99288344034ca2093ad2e9a558e3c5d0bb25f6ec882f93ce2e4bc2e041819a83
docker ps 能夠看到
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
99288344034c demo1 "npm start" 9 seconds ago Up 8 seconds 0.0.0.0:8080->8081/tcp wonderful_murdock
7.驗證
curl -i localhost:8080
瀏覽器也能夠輸入xxx.xxx.xxx.xxx(ip):8080