Docker深入淺出系列 | 容器初體驗


Docker深入淺出系列 | 容器初體驗

教程目標

Docker已經上市很多年,不是什么新鮮事物了,很多企業或者開發同學以前也不多不少有所接觸,但是有實操經驗的人不多,本系列教程主要偏重實戰,盡量講干貨,會根據本人理解去做闡述,具體官方概念可以查閱官方教程,本章目標如下:

  • 了解什么是Docker
  • 了解Docker解決了什么
  • 了解什么是鏡像和容器
  • 了解容器與虛擬機的區別
  • 了解Vagrant與Docker的區別
  • 了解Docker引擎和架構
  • 了解Docker的鏡像分層
  • 了解VirturalBox和Docker如何搭配使用
  • 了解主體機器如何與客體機器上的容器進行通信
  • 了解Vagrant、VirtualBox、Docker搭建與基本操作

預備工作

因為我是Mac用戶,所以這里VirturalBox和vagrant使用的是Mac版本,大家到官網各自下載對應的系統版本即可,強烈建議使用迅雷下載!

  • VirtualBox-6.0.14-133895-OSX.dmg
  • Vagrant_2.2.6_x86_64.dmg
  • Centos7鏡像

Vagrant下載

VirtualBox下載


容器與虛擬化技術

什么是Docker

簡單來說Docker是一款可以將應用程序與基礎設施分離、代碼及其所有依賴項打包,使應用程序能夠從一個計算環境快速可靠地運行到另一個計算環境,達到快速交付、測試、部署的容器化技術。

使用Linux容器部署應用程序稱為容器化。
在這里插入圖片描述

為什么要用Docker

我們可以反過來思考,不用Docker這些容器化技術會怎么樣,會遇到什么問題和瓶頸。

事例

想要發布一個應用到測試、生產環境使用,都會經歷以下流程:
在這里插入圖片描述

物理機時代

每個團隊會需要申請一台物理機作為測試開發環境,進行一系列的環境搭建
在這里插入圖片描述
通過上圖可以看出直接使用物理機會存在一些問題

  • 成本高 - 需要購買一台實體機器,沒辦法共享
  • 部署慢 - 發布一個應用需要走漫長的流程
  • 資源浪費 - 平時應用實際用不到那么多物理資源,除了搞活動時期,大部分時候處於閑置狀態,還有一部分資源被操作系統運行程序占用
  • 硬件限制 - 不同硬件廠商有兼容問題
  • 不利於遷移擴展 - 如果想遷移到其他服務器上,需要重頭打包配置應用依賴

虛擬化時代

在虛擬化技術出現之后,每個團隊只需要申請一台虛擬機,多台虛擬機可以共享同一台物理機,大大降低了成本,一定程度上提升了資源利用率,當公司搞活動時系統需要擴展,只需要通過虛擬機鏡像創建多個虛擬機即可,提升了系統擴展性和可用性
在這里插入圖片描述
Hypervisor,又稱虛擬機監視器(英語:virtual machine monitor,縮寫為 VMM),是用來建立與執行虛擬機器的軟件、固件或硬件。
被Hypervisor用來執行一個或多個虛擬機器的電腦稱為主體機器(host machine),這些虛擬機器則稱為客體機器(guest machine)。hypervisor提供虛擬的作業平台來執行客體操作系統(guest operating systems),負責管理其他客體操作系統的執行階段;這些客體操作系統,共同分享虛擬化后的硬件資源。(引用自百度百科)

從上圖不難發現,主機機器會為每個客體機器(虛擬機)提前分配好資源,與物理機時代一樣,實際上應用本身可能並不需要那么多物理資源,有一部分資源被操作系統所占用,大部分時候處於閑置狀態,仍然存在一些問題如下:

  • 資源利用率低 - 操作系統占用了一部分資源
  • 移植性差 - 虛擬機上的應用對操作系統有較大依賴
  • 啟動速度慢 - 每次運行一個虛擬機上的應用都需要先啟動系統
  • 部署麻煩 - 如果從開發環境切換到測試和生產環境,仍然需要重新搭建應用相關依賴

容器化時代

Docker容器類似沙箱,每個容器之間相互獨立、資源隔離、互不干擾,Docker容器化技術出現后,基本解決了上面提到的問題,Docker有以下優勢:

  • 啟動速度更快: 秒級啟動。
  • 快速的部署和交付: 開發者可以使用一個標准的鏡像來構建一套開發容器,開發完成之后, 運維人員可以直接使用這個容器來部署代碼。
  • 更高效的虛擬化: 它是內核級的虛擬化,因此可以實現更高的性能和效率。
  • 高效的遷移: Docker可以運行在不同的平台,用戶可以輕松的將一個應用從一個平台遷移到另一個平台。
  • 節省開支: Docker容器除了運行其中應用外,基本不消耗額外的系統資源,一台設備可以運行上千個容器。
  • 資源隔離:可以對Docker進行資源限制,每個容器可以享用自己的物理資源,互不干擾

在這里插入圖片描述
從上圖可以看到,我把物理資源變成可選了,這是因為默認的情況下,docker沒有對容器進行硬件資源的限制,當一台主機上運行幾百個容器,這些容器雖然互相隔離,但是底層卻使用着相同的 CPU、內存和磁盤資源。如果不對容器使用的資源進行限制,那么容器之間會互相影響,小的來說會導致容器資源使用不公平;大的來說,可能會導致主機和集群資源耗盡,服務完全不可用。

Docker提供資源隔離機制,利用Linux內核的 namespace機制來做容器之間的隔離,通過內核的 cgroups 機制來做容器的資源限制(CPU、Memory、Disk等)。

但是直接在主體機器安裝Docker,也會導致Docker容器直接依賴主體機器操作系統,沒辦法實現多租戶隔離,后面章節會提到對應解決方案。

什么是容器鏡像和容器

鏡像是一個可執行包,包含運行應用程序所需的所有內容——代碼、運行時、庫、環境變量和配置文件。容器是通過運行鏡像啟動容器,是鏡像的運行時實例。鏡像實際上就是一個容器的模板,通過這個模板可以創建很多相同的容器。

通過Java去類比理解Docker的一些概念:
在這里插入圖片描述

  • Class文件 - 相當於Docker鏡像,定義了類的一些所需要的信息
  • 對象 - 相當於容器,通過Class文件創建出來的實例
  • JVM - 相當於Docker引擎,可以讓Docker容器屏蔽底層復雜邏輯,實現跨平台操作

容器與虛擬機的區別

容器在Linux上本地運行,並與其他容器共享主機的內核。它運行一個獨立的進程,不占用比其他任何可執行程序更多的內存,使其輕量級。

虛擬機(VM) 運行一個成熟的“游客”操作系統,通過虛擬機監控程序對主機資源進行虛擬訪問。通常,vm提供的資源比大多數應用程序所需的要多。

在這里插入圖片描述
總的來說,容器不需要依賴操作系統,減少了很多系統資源開銷,使得容器可以更關注應用的需求,而虛擬機可以為每個應用靈活提供不同的操作系統,避免了docker容器直接依賴主體機器操作系統,兩者結合使用,可以讓整個系統架構更加靈活,擴展性更強。

Vagrant與Docker的區別

其實兩款產品沒有什么可比性,因為使用場景不同,這里列出來主要是避免一些童鞋誤解。
在這里插入圖片描述
Vagrant是一款管理虛擬機的工具,簡化了虛擬機的搭建和管理工作,不需要再像以前一樣,需要人工一個個去創建、啟動、停止虛擬機,可以通過vagrant腳本同一時間輕松搭建和管理多個虛擬機節點。

docker是一款用於快速交付、測試、部署的工具,簡化了應用環境的搭建和管理工作。兩者適用范圍不同。一個容器就是一個包含了應用執行所依賴的數據(包括lib,配置文件等等),Docker可以通過同一個鏡像文件快速在不同的環境(開發、測試、生產)搭建多個相同的容器。

Vagrant是用於管理虛擬機,Docker用於管理應用環境。

Docker引擎和架構

Docker引擎是一個客戶端-服務器應用程序,主要組件如下:

  • 服務器是一種長時間運行的程序,稱為守護進程(dockerd)
    命令)。
  • 一個REST API,它指定了程序可以用來與守護進程對話的接口
    指導它做什么。
  • 命令行接口(CLI)客戶端(docker命令)。

在這里插入圖片描述
平時我們使用的docker指令都是通過docker客戶端去與docker服務端進行通訊

Docker架構體系

Docker使用客戶機-服務器架構。

Docker客戶機與Docker守護進程進行對話,后者負責構建、運行和分發Docker容器。

Docker客戶機和守護進程可以在同一系統上運行,也可以將Docker客戶機連接到遠程Docker守護進程。Docker客戶機和守護進程通過UNIX套接字或網絡接口使用REST API進行通信。
在這里插入圖片描述

Docker的鏡像分層

Docker鏡像是由一系列層構成的。每一層代表鏡像Dockerfile中的一條指令。除了最后一層之外,每一層都是只讀的。Docker鏡像分層最大的好處是共享資源,其他相同環境的軟件鏡像都共同去享用同一個環境鏡像,而不需要每個軟件鏡像要去創建一個底層環境。
在這里插入圖片描述
上圖以Tomcat鏡像為例子,對於用戶而言,用戶面向的是一個疊加后的文件系統,我們對Tomcat容器做任何操作都會記錄在容器層,底層鏡像文件不會受影響。Docker容器底層共享主機內核,只保留少量運行Image必須的組件,在容器啟動時不需要啟動內核空間,所以啟動時比虛機較快,開銷少,易遷移。

VirturalBox和Docker如何搭配使用

上面章節也提到過,如果我們把Docker直接安裝在主體機器,會導致Docker直接依賴了我們主體機器的操作系統,如果不同的團隊共用一台物理機時,沒辦法做到每個團隊或每個環境都獨享自己的操作系統和相應的權限。
目前一般的部署模式有以下幾種:

  • 物理機+Docker模式 - 適合高I/O要求的業務,如一些數據庫服務、文件服務、緩存服務等
  • 虛擬機 - 虛擬機的多租戶的強隔離特性,保證租戶在擁有虛機root權限的同時,其他租戶和主機的安全
  • 物理機+虛擬機+Docker混合模式 - 集合上面的優點,既可以提供安全隔離,也能實現靈活擴展和高可用

在這里插入圖片描述
從上圖可以看出,本教程采用的是混合模式,Docker容器可以在虛擬機內部運行,虛擬機並為它們提供經過驗證的隔離,安全屬性,移動性,動態虛擬網絡等,可實現安全隔離和資源的高利用率。基本應該遵循:不同租戶的業務運行采用虛擬機隔離,相似類型的業務部署在同一組容器上的思路。

當虛擬機太多的時候,我們也沒辦法手動一個個去管理,因此這里用到Vagrant工具去管理虛擬機。

主體機器如何與客體機器上的容器進行通信

在這里插入圖片描述
從上圖可以看到,當我們使用Docker+虛擬機的混合模式時,實際上整體結構可以分為三大部分:主體機器、客體機器和容器。主體機器不能直接訪問客體機器上的容器的IP地址訪問容器,因為不再同一個網段,而要通過客體主機和對應的映射端口訪問客體機器的容器。

以Tomcat容器作為一個例子,這里虛擬機網絡模式默認是bridge方式,在實戰部分也有詳細步驟,應用部署圖如下:
在這里插入圖片描述
我在客體機器Centos上啟動一個Tomcat容器,容器端口為8080,映射端口為9090

docker run -d --name evan-tomcat -p 9090:8080 tomcat

通過命令查看得到,主體機器、客體機器、Tomcat容器IP地址(跟圖片一致)如下:

  • 主體機器 - 我機器自帶的MacOS,IP地址為 192.168.100.4
  • 客體機器 - 虛擬機上的Centos系統,IP地址為 192.168.100.9
  • 容器 - Tomcat容器(linux內核),IP地址為172.17.0.3

嘗試主體機器(MacOS)訪問客體機器(Centos)

192:~ evan$ ping 192.168.100.9
PING 192.168.100.9 (192.168.100.9): 56 data bytes
64 bytes from 192.168.100.9: icmp_seq=0 ttl=64 time=0.481 ms
64 bytes from 192.168.100.9: icmp_seq=1 ttl=64 time=0.477 ms
64 bytes from 192.168.100.9: icmp_seq=2 ttl=64 time=0.447 ms
64 bytes from 192.168.100.9: icmp_seq=3 ttl=64 time=0.339 ms
64 bytes from 192.168.100.9: icmp_seq=4 ttl=64 time=0.400 ms
64 bytes from 192.168.100.9: icmp_seq=5 ttl=64 time=0.324 ms

可以看到,主體機器是可以直接與客體機器進行通信,因為在同一個網段

嘗試客體機器(Centos)訪問Tomcat容器

[root@10 /]# ping 172.17.0.3
PING 172.17.0.3 (172.17.0.3) 56(84) bytes of data.
64 bytes from 172.17.0.3: icmp_seq=1 ttl=64 time=0.036 ms
64 bytes from 172.17.0.3: icmp_seq=2 ttl=64 time=0.043 ms
64 bytes from 172.17.0.3: icmp_seq=3 ttl=64 time=0.047 ms
64 bytes from 172.17.0.3: icmp_seq=4 ttl=64 time=0.042 ms

在虛擬機上可以直接與Tomcat容器進行通信

嘗試主體機器(MacOS)通過客體機器(Centos)端口9090訪問Tomcat容器

192:~ evan$ curl 192.168.100.9:9090
<!doctype html><html lang="en"><head><title>HTTP Status 404 – Not Found</title><style type="text/css">body {font-family:Tahoma,Arial,sans-serif;} h1, h2, h3, b {color:white;background-color:#525D76;} h1 {font-size:22px;} h2 {font-size:16px;} h3 {font-size:14px;} p {font-size:12px;} a {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style></head><body><h1>HTTP Status 404 – Not Found</h1><hr class="line" /><p><b>Type</b> Status Report</p><p><b>Message</b> Not found</p><p><b>Description</b> The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.</p><hr class="line" /><h3>Apache Tomcat/8.5.50</h3></body></html>192:~ evan$ 

可以看到主體機器可以通過客體機器IP+端口方式訪問容器,因此主體機器訪問的並不是容器真實的端口,而是虛擬機上端口的映射。


環境搭建與實戰

使用Vagrant管理虛擬機創建Centos7

1.創建一個centos7文件夾

mkdir centos7

2.在當前文件夾初始化Vagrantfile

vagrant init centos7

輸出結果如下:

192:centos7 evan$ vagrant init centos7
A `Vagrantfile` has been placed in this directory. You are now
ready to `vagrant up` your first virtual environment! Please read
the comments in the Vagrantfile as well as documentation on
`vagrantup.com` for more information on using Vagrant.

3.進入Vagrantfile,更改配置如下:

# -*- mode: ruby -*-
# vi: set ft=ruby :

# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure("2") do |config|
  # The most common configuration options are documented and commented below.
  # For a complete reference, please see the online documentation at
  # https://docs.vagrantup.com.

  # Every Vagrant development environment requires a box. You can search for
  # boxes at https://vagrantcloud.com/search.
  config.vm.box = "centos7"

  # Disable automatic box update checking. If you disable this, then
  # boxes will only be checked for updates when the user runs
  # `vagrant box outdated`. This is not recommended.
  # config.vm.box_check_update = false

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine. In the example below,
  # accessing "localhost:8080" will access port 80 on the guest machine.
  # NOTE: This will enable public access to the opened port
  # config.vm.network "forwarded_port", guest: 80, host: 8080

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine and only allow access
  # via 127.0.0.1 to disable public access
  # config.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "127.0.0.1"

  # Create a private network, which allows host-only access to the machine
  # using a specific IP.
  # config.vm.network "private_network", ip: "192.168.33.10"

  # Create a public network, which generally matched to bridged network.
  # Bridged networks make the machine appear as another physical device on
  # your network.
  config.vm.network "public_network"

  # Share an additional folder to the guest VM. The first argument is
  # the path on the host to the actual folder. The second argument is
  # the path on the guest to mount the folder. And the optional third
  # argument is a set of non-required options.
  # config.vm.synced_folder "../data", "/vagrant_data"

  # Provider-specific configuration so you can fine-tune various
  # backing providers for Vagrant. These expose provider-specific options.
  # Example for VirtualBox:
  #
  # config.vm.provider "virtualbox" do |vb|
  #   # Display the VirtualBox GUI when booting the machine
  #   vb.gui = true
  #
  #   # Customize the amount of memory on the VM:
  #   vb.memory = "1024"
  # end
    config.vm.provider "virtualbox" do |vb|
        vb.memory = "4000"
        vb.name= "evan-centos7"
        vb.cpus= 2
    end
  #
  # View the documentation for the provider you are using for more
  # information on available options.

  # Enable provisioning with a shell script. Additional provisioners such as
  # Puppet, Chef, Ansible, Salt, and Docker are also available. Please see the
  # documentation for more information about their specific syntax and use.
  # config.vm.provision "shell", inline: <<-SHELL
  #   apt-get update
  #   apt-get install -y apache2
  # SHELL
end

4.下載centos7鏡像文件
百度網盤下載
官網下載

5.將下載的鏡像文件保存到你系統的一個目錄下,我本機的存放目錄是:

/Users/evan/development/visualbox/virtualbox.box

6.將centos7鏡像文件添加到vagrant管理的鏡像中,並將鏡像命名為centos7

 vagrant box add centos7 /Users/evan/development/visualbox/virtualbox.box

添加成功輸出結果如下:

 192:visualbox evan$ vagrant box add centos7 /Users/evan/development/visualbox/virtualbox.box
==> box: Box file was not detected as metadata. Adding it directly...
==> box: Adding box 'centos7' (v0) for provider: 
    box: Unpacking necessary files from: file:///Users/evan/development/visualbox/virtualbox.box
==> box: Successfully added box 'centos7' (v0) for 'virtualbox'!

7.查看已添加的虛擬機鏡像,可通過vagrant box list

192:visualbox evan$ vagrant box list
centos7 (virtualbox, 0)

可以看到,已經成功添加centos7

8.根據Vagrantfile文件啟動創建虛擬機,去到剛才初始化Vagrantfile的文件夾,執行vagrant up創建虛擬機,vagrant會自動根據我們在Vagrant配置好的參數來創建虛擬機,注意我們上面添加的虛擬機名字centos7要與配置文件中的config.vm.box = "centos7"一致。(執行過程中,Virtualbox應用不需要打開)

192:centos7 evan$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Clearing any previously set forwarded ports...
==> default: Clearing any previously set network interfaces...
==> default: Available bridged network interfaces:
1) en0: Wi-Fi (Wireless)
2) en5: USB Ethernet(?)
3) p2p0
4) awdl0
5) llw0
6) en7: USB 10/100/1000 LAN
7) en1: Thunderbolt 1
8) en2: Thunderbolt 2
9) en3: Thunderbolt 3
10) en4: Thunderbolt 4
11) bridge0
==> default: When choosing an interface, it is usually the one that is
==> default: being used to connect to the internet.
    default: Which interface should the network bridge to? 1
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
    default: Adapter 2: bridged
==> default: Forwarding ports...
    default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
    default: 
    default: Vagrant insecure key detected. Vagrant will automatically replace
    default: this with a newly generated keypair for better security.
    default: 
    default: Inserting generated public key within guest...
    default: Removing insecure key from the guest if it's present...
    default: Key inserted! Disconnecting and reconnecting using new SSH key...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
    default: No guest additions were detected on the base box for this VM! Guest
    default: additions are required for forwarded ports, shared folders, host only
    default: networking, and more. If SSH fails on this machine, please install
    default: the guest additions and repackage the box to continue.
    default: 
    default: This is not an error message; everything may continue to work properly,
    default: in which case you may ignore this message.
==> default: Configuring and enabling network interfaces...
==> default: Rsyncing folder: /Users/evan/development/centos7/ => /vagrant

執行完畢,可以打開Visualbox查看是否已經多了一個centos7虛擬機
在這里插入圖片描述

在虛擬機安裝Docker

安裝Docker之前,需要進入剛才安裝好的Centos7操作系統,因此需要先設置下SSH配置,這里使用的是賬號密碼登陸

通過SSH客戶端訪問Centos

1.使用vagrant ssh 命令進入虛擬機

192:centos7 evan$ vagrant ssh
-bash: warning: setlocale: LC_CTYPE: cannot change locale (UTF-8): No such file or directory
[vagrant@10 ~]$ ls

2.執行sudo -i命令切換到root用戶,然后進入通過vi /etc/ssh/sshd_config命令修改SSH安全認證配置

[vagrant@10 ~]$ sudo -i
[root@10 ~]# vi /etc/ssh/sshd_config

3.修改SSH安全認證如下

PasswordAuthentication yes

4.修改完成,退出sshd_config后,更換SSH登陸密碼,我這里使用的密碼是evan123

[root@10 ~]# passwd
Changing password for user root.
New password: 
BAD PASSWORD: The password fails the dictionary check - it is too simplistic/systematic
Retype new password: 
passwd: all authentication tokens updated successfully.

5.重啟SSH服務,使配置生效

[root@10 ~]# systemctl restart sshd

6.測試SSH連接
查看當前Centos系統ip,通過ip add命令進行查看

[root@10 /]# ip add
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 52:54:00:8a:fe:e6 brd ff:ff:ff:ff:ff:ff
    inet 10.0.2.15/24 brd 10.0.2.255 scope global noprefixroute dynamic eth0
       valid_lft 74572sec preferred_lft 74572sec
    inet6 fe80::5054:ff:fe8a:fee6/64 scope link 
       valid_lft forever preferred_lft forever
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 08:00:27:ba:0a:28 brd ff:ff:ff:ff:ff:ff
    inet 192.168.100.9/24 brd 192.168.100.255 scope global noprefixroute dynamic eth1
       valid_lft 160972sec preferred_lft 160972sec
    inet6 fe80::a00:27ff:feba:a28/64 scope link 
       valid_lft forever preferred_lft forever

可以看到,當前外網ip是192.168.100.9

退出虛擬機,回到主體機器,測試是否可以連接上虛擬機上的Centos系統

192:~ evan$ ssh root@192.168.100.9
The authenticity of host '192.168.100.9 (192.168.100.9)' can't be established.
ECDSA key fingerprint is SHA256:1yutVoFjWAa0o2vCNP+kOxS/rITjxhqTV/48XsTNKGo.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.100.9' (ECDSA) to the list of known hosts.
root@192.168.100.9's password: 
Last login: Mon Jan 27 12:19:55 2020 from 127.0.0.1
-bash: warning: setlocale: LC_CTYPE: cannot change locale (UTF-8): No such file or directory
[root@10 ~]# 

此時已經成功連接上,下一步開始Docker安裝

在Centos上安裝Docker

1.執行以下命令清理之前已安裝的Docker文件,如果之前曾經安裝過

sudo yum remove docker \
                  docker-client \
                  docker-client-latest \
                  docker-common \
                  docker-latest \
                  docker-latest-logrotate \
                  docker-logrotate \
                  docker-engine

因為這個系統是新安裝,之前沒有Docker相關文件,執行結果如下:

[root@10 /]# sudo yum remove docker \
>                   docker-client \
>                   docker-client-latest \
>                   docker-common \
>                   docker-latest \
>                   docker-latest-logrotate \
>                   docker-logrotate \
>                   docker-engine
Failed to set locale, defaulting to C
Loaded plugins: fastestmirror
No Match for argument: docker
No Match for argument: docker-client
No Match for argument: docker-client-latest
No Match for argument: docker-common
No Match for argument: docker-latest
No Match for argument: docker-latest-logrotate
No Match for argument: docker-logrotate
No Match for argument: docker-engine
No Packages marked for removal

2.輸入以下命令安裝環境必要依賴

sudo yum install -y yum-utils \
    device-mapper-persistent-data \
    lvm2

3.通過以下命令配置阿里雲鏡像加速器,否則下載鏡像會比較慢,這里鏡像加速器做了脫敏處理,大家可以自己去申請一個

sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["https://***.mirror.aliyuncs.com"]
}
EOF
sudo systemctl daemon-reload
sudo systemctl restart docker

怎么獲取鏡像加速器地址,可以查看我另一篇文章
使用Docker安裝Oracle
在這里插入圖片描述

4.設置Docker倉庫,Docker默認倉庫hub.docker.com

 sudo yum-config-manager \
      --add-repo \
      https://download.docker.com/linux/centos/docker-ce.repo

5.安裝Docker

sudo yum install -y docker-ce docker-ce-cli containerd.io

6.啟動Docker服務

sudo systemctl start docker

7.通過Docker倉庫自帶鏡像,測試Docker是否已經安裝成功

[root@10 /]# sudo docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
1b930d010525: Pull complete 
Digest: sha256:9572f7cdcee8591948c2963463447a53466950b3fc15a247fcad1917ca215a2f
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    (amd64)
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://hub.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/get-started/

Docker會自動下載鏡像,如果在本地查找不到

通過Docker安裝Tomcat

1.從遠方倉庫拉去Tomcat鏡像,這里不帶版本號默認拉取最新版本

docker pull tomcat

2.啟動Tomcat容器,指定容器命名為evan-tomcat,並且配置容器端口9090映射到內置mysql 3306端口

docker run -d --name evan-tomcat -p 9090:8080 tomcat

通過Docker安裝Mysql

1.從遠方倉庫拉去Tomcat鏡像,這里不帶版本號默認拉取最新版本

docker pull mysql

2.啟動MySQL容器,並改名為evan-mysql,配置容器端口 3301映射到3306端口,並設置密碼為evan123

docker run -d --name evan-mysql -p 3301:3306 -e MYSQL_ROOT_PASSWORD=evan123 --privileged mysql

檢查容器是否啟動

1.通過以下Docker指令可以查看上面我們安裝和啟動的容器是否正常運行:

[root@10 /]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                               NAMES
358207fa8d8b        tomcat              "catalina.sh run"        3 minutes ago       Up 3 minutes        0.0.0.0:9090->8080/tcp              evan-tomcat
b58999f0524f        mysql               "docker-entrypoint.s…"   5 minutes ago       Up 5 minutes        33060/tcp, 0.0.0.0:3301->3306/tcp   evan-mysql
[root@10 /]# 

2.我們可以通過上面的容器ID去進入到容器內部,這里以Tomcat為例子:

[root@10 /]# docker exec -it 358207fa8d8b /bin/bash
root@358207fa8d8b:/usr/local/tomcat# ls
BUILDING.txt	 LICENSE  README.md	 RUNNING.txt  conf     lib   native-jni-lib  webapps	   work
CONTRIBUTING.md  NOTICE   RELEASE-NOTES  bin	      include  logs  temp	     webapps.dist
root@358207fa8d8b:/usr/local/tomcat# 

這樣我們本章所有環境SETUP已經順利完成,后面的章節將會更深入介紹容器的原理、集群部署、管理以及結合真實微服務的應用。


Q&A

1.在Mac中安裝Visualbox時失敗,提示“the installation failed”
原因是MacOS阻止了VirtualBox安裝kernel extension。在system preferences中選擇security&privacy在general中點擊下方的allow即可解決。

2.vagrant up命令啟動失敗,提示No Usable default provider could be found for your system
這是由於Vagrant與Virtualbox版本不一致,Vagrant的版本比Virtualbox的舊,可以將Virtualbox降級,或者直接使用本文推薦的版本

附錄

Vagrant常用命令

  • vagrant up
    啟動虛擬機
  • vagrant ssh
    進入虛擬機
  • )vagrant status
    查看centos7的狀態
  • vagrant halt
    停止/關閉centos7
  • vagrant destroy
    刪除centos7
  • vagrant status
    查看當前vagrant創建的虛擬機
  • Vagrantfile中也可以寫腳本命令,使得centos7更加豐富
    但是要注意,修改了Vagrantfile,要想使正常運行的centos7生效,必須使用vagrant reload

Docker常用命令

  • docker pull
    拉取鏡像到本地
  • docker run
    根據某個鏡像創建容器
  • -d 讓容器在后台運行,其實就是一個進程
  • --name 給容器指定一個名字
  • -p 將容器的端口映射到宿主機的端口
  • docker exec -it
    進入到某個容器中並交互式運行

有興趣的朋友,歡迎加我公眾號一起交流,有問題可以留言,平時工作比較忙,我也抽時間盡量回復每位朋友的留言,謝謝!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM