假設咱們的項目名爲express
,在express
項目中建立編輯Dockerfile
文件:node
$ vim Dockerfile FROM node:latest RUN mkdir -p /home/www/express WORKDIR /home/www/express COPY . /home/www/express RUN npm install EXPOSE 3000 ENTRYPOINT ["npm", "run"] CMD ["start"]
這個文件包含了如下命令:docker
FROM node:latest
- 指定使用最新版本的node基礎鏡像RUN mkdir -p /home/www/express
- 在容器內建立/home/www/express目錄WORKDIR /home/www/express
- 將容器內工做目錄設置爲/home/www/expressCOPY . /home/www/express
- 將宿主機當前目錄下內容複製到鏡像/home/www/express目錄下RUN npm install
- npm install安裝應用所需的NPM包EXPOSE 3000
- 對外開放容器的3000端口ENTRYPOINT ["npm", "run"]
- 容器啓動後執行的命令。不可被docker run
提供的參數覆蓋CMD ["start"]
- 在容器啓動時,執行的命令,可被docker run
提供的參數覆蓋編寫完Dockerfile文件後,就能夠經過docker build命令來構建鏡像:express
$ sudo docker build -t test/express .
咱們經過-t參數,將鏡像命名爲test/express。構建過程相似以下:npm
Sending build context to Docker daemon 29.7 kB Step 1/8 : FROM registry.src.followme.com:5000/node:v1 ---> c99c549e8227 Step 2/8 : RUN mkdir -p /home/www/express-app ---> Running in 8be9a90629b0 ---> b9f584851225 Removing intermediate container 8be9a90629b0 Step 3/8 : WORKDIR /home/www/express-app ---> 5072c31f9dd9 Removing intermediate container e9dbf4ce3d8b Step 4/8 : COPY . /home/www/express-app ---> a4d1725f15ed Removing intermediate container 30aa49765015 Step 5/8 : RUN yarn ---> Running in f181c243deaa yarn install v1.3.2 [1/4] Resolving packages... [2/4] Fetching packages... [3/4] Linking dependencies... [4/4] Building fresh packages... Done in 9.46s. ---> d390931d73e6 Removing intermediate container f181c243deaa Step 6/8 : EXPOSE 3000 ---> Running in 94101ab38864 ---> 43199a8a5a90 Removing intermediate container 94101ab38864 Step 7/8 : ENTRYPOINT npm run ---> Running in 80b1318962cf ---> 6b203c50e855 Removing intermediate container 80b1318962cf Step 8/8 : CMD start ---> Running in a9909e537f59 ---> d56eae48377c Removing intermediate container a9909e537f59 Successfully built d56eae48377c
鏡像構建完成後,能夠經過所構建的鏡像建立/運行容器,從而實現express應用的 Docker 化部暑。vim
使用tets/express鏡像運行一個容器:app
$ sudo docker run -d --name experss-app -p 3000:3000 test/express
在以上操做中,咱們經過test/express
鏡像運行了容器,並將容器命名爲experss-app
。運行容器,咱們還指定了-d
參數,該參數使容器之後臺的方式運行。而-p
參數將宿主機的3000端口映射到了容器的3000端口。運行容器後,能夠經過docker ps命令看到運行中的容器。此時可經過localhost:3000
訪問服務。ui