docker下node环境搭建
阅读原文时间:2023年07月10日阅读:1

以下操作必须已经安装了NodeJS。

⾸先创建⼀个空⽂件夹。并创建以下⽂件:

server.js

package.json

Dockerfile

.dockerignore

然后在server.js写⼊

const koa = require('koa');
const app = new koa();

app.use(async ctx =>{
    ctx.body = "Hello docker";
});
app.listen(3000);

在package.json中写⼊

{
"name":"docker_demo",
"version":"0.1.0",
"private:true",
"script":{
"start":"node server.js"
},
"dependencies":{
"koa":"^2.5.0"
}
}


npm start

创建dockerfile文件

Dockerfile是由⼀系列命令和参数构成的脚本,⼀个Dockerfile⾥⾯包含了构建整个image的完整命

令。Docker通过docker build执⾏Dockerfile中的⼀系列命令⾃动构建image. 在.dockerignore⽂件⾥

⾯写⼊代码。表示过滤该类型的⽂件。类似git的.gitignore

.dockerignore

# Logs
logs
*.log
npm-debug.log*
# Runtime data
pids
*.pid
*.seed
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (http://gruntjs.com/creatingplugins#storing-task-files)
.grunt
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules
jspm_packages
# Optional npm cache directory
.npm
# Optional REPL history
.node_repl_history
.idea
.node_modules
node_modules
.vscode


[root@Sandbox-N ~]# docker build -t docker_demo .
Sending build context to Docker daemon 39.94kB
Step 1/7 : FROM node:8.9-alpine
---> 406f227b21f5
Step 2/7 : MAINTAINER robin
---> Using cache
---> 78d6cdbcfee2
Step 3/7 : ADD . /app/
---> 2cb30678612d
Step 4/7 : WORKDIR /app
Removing intermediate container e51377081039
---> c2b7d0f37d2d
Step 5/7 : RUN npm install
---> Running in da0c3946ca8d
npm notice created a lockfile as package-lock.json. You should commit
this file.
added 38 packages in 3.323s
Removing intermediate container da0c3946ca8d
---> eecee87f10e2
Step 6/7 : EXPOSE 3000
---> Running in f3973cc168a4
Removing intermediate container f3973cc168a4
---> 2671a4c6deb4
Step 7/7 : CMD ["npm", "start"]
---> Running in dec529f754aa
Removing intermediate container dec529f754aa
---> 6ec73793d353
Successfully built 6ec73793d353
Successfully tagged docker_demo:lates

等待镜像构造完成。然后使⽤ images命令查看镜像

此时可以看到images已经构造完成。现在开始启动images,并测试。

# 启动镜像 -d表示后台执⾏,-p 9000:3000表示指定本地的9000端⼝隐射到容器内的3000端,
docker_demo为镜像名称
docker run -d -p 9000:3000 docker_demo
#查看容器
docker ps

如果此时本地⽆法打开。可以使⽤log命令查看⽇志。根据⽇志修改对应出现的对⽅