前言
docker是一個開源的應用容器引擎,可以為我們提供安全、可移植、可重復的自動化部署的方式。docker采用虛擬化的技術來虛擬化出應用程序的運行環境。如上圖一樣。docker就像一艘輪船。而輪船上面的每個小箱子可以看成我們需要部署的一個個應用。使用docker可以充分利用服務器的系統資源,簡化了自動化部署和運維的繁瑣流程,減少很多因為開發環境中和生產環境中的不同引發的異常問題。從而提高生產力。
docker三個核心概念如下:
鏡像(images):一個只讀的模板,可以理解為應用程序的運行環境,包含了程序運行所依賴的環境和基本配置。相當于上圖中的每個小箱子里面裝的東西。 倉庫(repository):一個用于存放鏡像文件的倉庫。可以看做和gitlab一樣。 容器(container):一個運行應用程序的虛擬容器,他和鏡像最大的區別在于容器的最上面那一層是可讀可寫的。 相當于上圖中的每個小箱子里。本文主要是教大家了解如何在Docker容器中設置Node JS:
有一個可運行工作的NodeJS應用程序
通過確保進程在出錯時不退出,使節點應用程序具有彈性
通過在代碼更改時自動重新啟動服務器,使Node應用程序易于使用
利用Docker:
先決條件
Docker已經安裝好了
至少入門級節點知識和NPM
1.獲取一個簡單的Node應用程序
我們將使用Express,因為它的設置是容易的。
在一個干凈的目錄中,讓我們從初始化NPM開始,繼續運行此命令并按照提示進行操作:
npm init
安裝Express:
npm install --save-prod express
編制代碼src/index.js
<b>const</b> express = require('express')<b>const</b> app = express()<b>const</b> port = 3000app.get('/', (req, res) => res.send('Hello World!'))app.listen(port, () => {console.log(`Example app listening on port ${port}!`))啟動一個偵聽端口3000并使用Hello World響應的"/"這個URL路由。
2.設置Docker以運行我們的Node應用程序
我們將使用docker-compose.yml文件來啟動和停止我們的Docker容器,而不是鍵入長長的Docker命令。您可以將此文件視為多個Docker容器的配置文件。
docker-compose.yml:
version: "3"services: app: container_name: app # How the container will appear when listing containers from the CLI image: node:10 # The <container-name>:<tag-version> of the container, in this case the tag version aligns with the version of node user: node # The user to run as in the container working_dir: "/app" # Where to container will assume it should run commands and where you will start out if you go inside the container networks: - app # Networking can get complex, but for all intents and purposes just know that containers on the same network can speak to each other ports: - "3000:3000" # <host-port>:<container-port> to listen to, so anything running on port 3000 of the container will map to port 3000 on our localhost volumes: - ./:/app # <host-directory>:<container-directory> this says map the current directory from your system to the /app directory in the docker container command: "node src/index.js" # The command docker will execute when starting the container, this command is not allowed to exit, if it does your container will stopnetworks: app:
新聞熱點
疑難解答
圖片精選