Dockerfile 制作 NodeJS 服务端应用
- 准备好一个简单的 http 应用
vim index.js # vi / vim 请随意
index.js 内容:
let http = require("http");
http.createServer( (request, response) => {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
- 创建 Dockerfile
vim Dockerfile
Dockerfile 内容:
FROM node:latest
ADD index.js /index.js
CMD node index.js
FROM node:latest:以 node:latest 为 base 镜像;
ADD index.js /index.js:将步骤1中创建的 index.js 添加到新镜像中;
CMD node index.js:在容器启动时运行,启动 http 应用
- build 镜像
docker build -t node-app-server .
-t 指定镜像名称
最后的 . 指明 build context 为当前目录,也就是说需要在 Dockfile 所在目录运行上面这个命令;当然,也可以通过 -f 参数指定 Dockerfile 的位置。
docker images # 查看所有镜像
- 运行 node-hello-world
docker run -p 80:8081 -d node-app-server
-p 80:8081 将容器 8081 端口映射到宿主机的 80 端口
-d 以后台模式运行 node-app-server
docker ps # 查看 docker 进程
curl 127.0.0.1 # 访问容器中的 http 应用