1. 程式人生 > >構建自定義Docker容器例項

構建自定義Docker容器例項

測試工程NodeHello

在此資料夾下,有檔案Dockerfile、hi.js。Dockerfile內容為

FROM node:7.9.0

COPY .  /app

WORKDIR /app

hi.js內容為:
var http=require("http")
var url=require("url");
var util=require("util");

function onRequest(request, response){
	console.log("Request received");
	var pathName = url.parse(request.url).pathname;
	console.log("Request path: " + pathName);	
		

	response.writeHead(200, {"Content-Type":"text/plain"});
	//response.write("Hello World");
	//response.write(util.inspect(url.parse(request.url, true)));
	var params = url.parse(request.url, true).query;
	response.write("site name: " + params.name);
	response.write("\n");
	response.write("site url: " + params.url);
	
	response.end();
}
	
http.createServer(onRequest).listen(8888);
console.log("Server has started");

編譯Docker

切換到NodeHello目錄下

sudo docker build -t sim/nodehello-docker  .
執行結果如下:
Sending build context to Docker daemon  3.584kB
Step 1/3 : FROM node:7.9.0
7.9.0: Pulling from library/node
cd0a524342ef: Pull complete 
e39c3ffe4133: Pull complete 
85334a7c2001: Pull complete 
4c546d9d6a84: Pull complete 
fa1ae2b8eedb: Pull complete 
2e2f1cff6e9f: Pull complete 
aa7b15936229: Pull complete 
04b1d7bd151d: Pull complete 
Digest: sha256:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Status: Downloaded newer image for node:7.9.0
 ---> 90223b3d894e
Step 2/3 : COPY . /app
 ---> 2021694e684d
Removing intermediate container d49c59e28b08
Step 3/3 : WORKDIR /app
 ---> fbc14c07e266
Removing intermediate container 0a40d8f98dbf
Successfully built fbc14c07e266
Successfully tagged sim/nodehello-docker:late

執行容器

執行容器並將內部8888埠對映到外部的3001埠

docker run -d -p 3001:8888 sim/nodehello-docker   node ./hi.js

訪問容器內的Web服務