您的位置:首页 > 运维架构 > Docker

如何用Docker建立一个Node.js的开发环境

2017-10-20 17:32 826 查看
 

建立一个文件夹

用管理员身份打开powershell.

在文件夹下面运行npm init, 根据提示填入信息,以便产生一个package.json文件。

在文件中加入需要的dependencies,例如:

{

"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.13.3"

}

}
 

4. 创建一个app.js文件,例如:

const express = require('express')

const app = express()

 

app.get('/', function (req, res) {

res.send('Hello World!')

})

 

app.listen(3000, function () {

console.log('Example app listening on port 3000!')

})

 

5. 创建一个空文件名字为Dockerfile,填入如下内容:

FROM node:boron

 

# Create app directory

WORKDIR /app

 

# Install app dependencies

COPY package.json .

# For npm@5 or later, copy package-lock.json as well

# COPY package.json package-lock.json ./

 

RUN npm install

 

# Bundle app source

COPY . .

 

EXPOSE 3000

CMD [ "node", "app.js" ]

 

6. 创建名为.dockerignore的文件,并输入如下的内容:

node_modules

npm-debug.log

 

这是为了防止本地的module和debug log被拷贝进docker image.

(我这一步无法做,因为没有办法创建这样的文件,总是要求必须有文件名。需要进一步调查)

7. Build image

docker build -t nodehello .

 

8. 运行image.

docker run -p 3000:3000 -d nodehello

 

如果运行成功,会出现Example app listening on port 3000的字样。

 

这时访问http://localhhost:3000 就可以访问app.js中定义的内容了。

 

参考文章:


https://nodejs.org/en/docs/guides/nodejs-docker-webapp/

https://www.distelli.com/docs/tutorials/build-and-deploy-nodejs-with-docker/

https://expressjs.com/en/starter/hello-world.html

https://docs.docker.com/get-started/part2/#build-the-app

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: