Try   HackMD

Vagrant 介紹與基本操作

tags:Vagrant VirtualBox Hypervisor Configuration management

01. 虛擬化技術(Virtualization)介紹

1-1 虛擬化技術分類

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

1-2 虛擬機安裝方式分類

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

02. Vagrant 簡介

  1. Vagrant 由 HashiCorp 開發

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
Terraform 也是由 HashiCorp 開發

  • Terraform:infrastructure as code software which enables provisioning and adapting virtual infrastructure across all major cloud providers.
  • The primary usage of Terraform is for managing remote resources in cloud providers such as AWS. Terraform is designed to be able to manage extremely large infrastructures that span multiple cloud providers. Vagrant is designed primarily for local development environments that use only a handful of virtual machines at most.
  • Vagrant is for development environments. Terraform is for more general infrastructure management.
  1. 用於構建和管理虛擬機環境的工具。
  2. 提供易於配置(configure)、可重現(reproducible)和可攜性(portable)的工作環境。
  3. 支援 Shell 腳本、Chef 或 Puppet 等標準配置工具,可以在虛擬機上自動安裝和配置軟體。

Introduction to Vagrant
Vagrant vs. Terraform

03. Vagrant 運作方式及軟體安裝

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

軟體 版本 Download
Vagrant 2.3.4 Windows (AMD64)MacOS (AMD64)Linux (X86_64)
VirtualBox 6.1.40 WindowsMacOSLinux (Ubuntu 20.04)
Visual Studio Code 1.73 Windows、MacOS、Linux

04. Vagrant 基本操作介紹

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Git Hub Download

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
本次 Demo Vagrantfile
Virtualization (VT-x/AMD-V) - Enabling virtualization on your computer
Vagrant Cloud - Discover Vagrant Boxes
Official Boxes

  1. HashiCorp (the makers of Vagrant) publish a basic Ubuntu 18.04 64-bit box that is available for minimal use cases. It is highly optimized, small in size, and includes support for VirtualBox, Hyper-V, and VMware.
  2. For other users, we recommend the Bento boxes. The Bento boxes are open source and built for a number of providers including VMware, VirtualBox, and Parallels. There are a variety of operating systems and versions available.

4-1 從既有的 Vagrantfile 啟動虛擬機

  1. 切換至 .\docker-install 並執行 vagrant up
    • row 18:配置 Private Key
    • row 32:開始執行 shell 安裝 docker
PS C:\Users\User> cd D:\RCC-sharing\vagrant-demo\docker-install PS D:\RCC-sharing\vagrant-demo\docker-install> vagrant up Bringing machine 'dockerlab' up with 'virtualbox' provider... ==> dockerlab: Importing base box 'bento/ubuntu-20.04'... ==> dockerlab: Matching MAC address for NAT networking... ==> dockerlab: Checking if box 'bento/ubuntu-20.04' version '202206.03.0' is up to date... ==> dockerlab: Setting the name of the VM: docker-install_dockerlab_1661968490242_57863 ==> dockerlab: Clearing any previously set network interfaces... ==> dockerlab: Preparing network interfaces based on configuration... dockerlab: Adapter 1: nat ==> dockerlab: Forwarding ports... dockerlab: 22 (guest) => 2222 (host) (adapter 1) ==> dockerlab: Running 'pre-boot' VM customizations... ==> dockerlab: Booting VM... ==> dockerlab: Waiting for machine to boot. This may take a few minutes... dockerlab: SSH address: 127.0.0.1:2222 dockerlab: SSH username: vagrant dockerlab: SSH auth method: private key dockerlab: Warning: Connection reset. Retrying... dockerlab: Warning: Connection aborted. Retrying... dockerlab: dockerlab: Vagrant insecure key detected. Vagrant will automatically replace dockerlab: this with a newly generated keypair for better security. dockerlab: dockerlab: Inserting generated public key within guest... dockerlab: Removing insecure key from the guest if it's present... dockerlab: Key inserted! Disconnecting and reconnecting using new SSH key... ==> dockerlab: Machine booted and ready! (略) ==> dockerlab: Running provisioner: shell... dockerlab: Running: inline script dockerlab: Reading package lists... (略)
  1. 驗證虛擬機狀態 vagrant status
    • row 4:虛擬機狀態為 running
PS D:\RCC-sharing\vagrant-demo\docker-install> vagrant status Current machine states: dockerlab running (virtualbox) The VM is running. To stop this VM, you can run `vagrant halt` to shut it down forcefully, or you can run `vagrant suspend` to simply suspend the virtual machine. In either case, to restart it again, simply run `vagrant up`.

4-2 進入虛擬機訪問 Guest OS

  1. 登入方式-01:vagrant ssh
PS D:\RCC-sharing\vagrant-demo\docker-install> vagrant ssh Welcome to Ubuntu 20.04.4 LTS (GNU/Linux 5.4.0-110-generic x86_64) * Documentation: https://help.ubuntu.com * Management: https://landscape.canonical.com * Support: https://ubuntu.com/advantage System information as of Thu 01 Sep 2022 05:20:56 AM UTC System load: 0.0 Processes: 126 Usage of /: 14.7% of 30.63GB Users logged in: 0 Memory usage: 18% IPv4 address for docker0: 172.17.0.1 Swap usage: 0% IPv4 address for eth0: 10.0.2.15 This system is built by the Bento project by Chef Software More information can be found at https://github.com/chef/bento Last login: Wed Aug 31 18:03:00 2022 from 10.0.2.2
  1. 登入方式-02:ssh -i
PS D:\RCC-sharing\vagrant-demo\docker-install> vagrant ssh-config Host dockerlab HostName 127.0.0.1 User vagrant Port 2222 UserKnownHostsFile /dev/null StrictHostKeyChecking no PasswordAuthentication no IdentityFile D:/RCC-sharing/vagrant-demo/docker-install/.vagrant/machines/dockerlab/virtualbox/private_key IdentitiesOnly yes LogLevel FATAL PS D:\RCC-sharing\vagrant-demo\docker-install> ssh -i D:/RCC-sharing/vagrant-demo/docker-install/.vagrant/machines/dockerlab/virtualbox/private_key vagrant@127.0.0.1 -p 2222 Welcome to Ubuntu 20.04.4 LTS (GNU/Linux 5.4.0-110-generic x86_64) * Documentation: https://help.ubuntu.com * Management: https://landscape.canonical.com * Support: https://ubuntu.com/advantage System information as of Thu 01 Sep 2022 08:14:18 AM UTC System load: 0.02 Processes: 125 Usage of /: 14.7% of 30.63GB Users logged in: 0 Memory usage: 18% IPv4 address for docker0: 172.17.0.1 Swap usage: 0% IPv4 address for eth0: 10.0.2.15 This system is built by the Bento project by Chef Software More information can be found at https://github.com/chef/bento Last login: Thu Sep 1 07:16:54 2022 from 10.0.2.2

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
無法透過 ssh -i 登入處理方式

  • 確認目錄 ~/.ssh 是否有先前產生的檔案 known_hosts ,刪除後就能成功透過密碼登入虛擬機
  1. 登入方式-03:ssh -p [port] vagrant@127.0.0.1
PS D:\RCC-sharing\vagrant-demo\docker-install> vagrant ssh-config Host dockerlab HostName 127.0.0.1 User vagrant Port 2222 UserKnownHostsFile /dev/null StrictHostKeyChecking no PasswordAuthentication no IdentityFile D:/RCC-sharing/vagrant-demo/docker-install/.vagrant/machines/dockerlab/virtualbox/private_key IdentitiesOnly yes LogLevel FATAL PS D:\RCC-sharing\vagrant-demo\docker-install> ssh -p 2222 vagrant@127.0.0.1 vagrant@127.0.0.1's password: Welcome to Ubuntu 20.04.4 LTS (GNU/Linux 5.4.0-110-generic x86_64) * Documentation: https://help.ubuntu.com * Management: https://landscape.canonical.com * Support: https://ubuntu.com/advantage System information as of Thu 01 Sep 2022 08:33:20 AM UTC System load: 0.09 Processes: 128 Usage of /: 14.2% of 30.63GB Users logged in: 0 Memory usage: 17% IPv4 address for docker0: 172.17.0.1 Swap usage: 0% IPv4 address for eth0: 10.0.2.15 This system is built by the Bento project by Chef Software More information can be found at https://github.com/chef/bento Last login: Thu Sep 1 08:32:02 2022 from 10.0.2.2
調整 sshd_config,設定 PasswordAuthentication 的 Permission Policy
vagrant@docker-lab:/etc/ssh$ sudo vim sshd_config # To disable tunneled clear text passwords, change to no here! PasswordAuthentication yes | no #PermitEmptyPasswords no vagrant@docker-lab:/etc/ssh$ sudo systemctl restart sshd vagrant@docker-lab:/etc/ssh$ exit logout

登入測試 Permission denied

PS D:\RCC-sharing\vagrant-demo\docker-install> ssh -p 2222 vagrant@127.0.0.1 vagrant@127.0.0.1: Permission denied (publickey).

4-3 暫停或重啟虛擬機

  1. 暫停虛擬機 vagrant suspend
PS D:\RCC-sharing\vagrant-demo\docker-install> vagrant suspend ==> dockerlab: Saving VM state and suspending execution...
  1. 重啟虛擬機 vagrant resume
PS D:\RCC-sharing\vagrant-demo\docker-install> vagrant resume ==> dockerlab: Resuming suspended VM... ==> dockerlab: Booting VM... ==> dockerlab: Waiting for machine to boot. This may take a few minutes... dockerlab: SSH address: 127.0.0.1:2222 dockerlab: SSH username: vagrant dockerlab: SSH auth method: private key ==> dockerlab: Machine booted and ready! ==> dockerlab: Machine already provisioned. Run `vagrant provision` or use the `--provision` ==> dockerlab: flag to force provisioning. Provisioners marked to run always will still run.

4-4 停止並刪除虛擬機

加入 -f 選項強制刪除虛擬機 vagrant destroy -f

PS D:\RCC-sharing\vagrant-demo\docker-install> vagrant destroy -f ==> dockerlab: Forcing shutdown of VM... ==> dockerlab: Destroying VM and associated drives...

4-5 製作 Vagrantfile

透過 vagrant init 初始化一個新的 Vagrant 環境

PS C:\Users\User> cd D:\RCC-sharing\vagrant-demo\docker-install PS D:\RCC-sharing\vagrant-demo\docker-install> vagrant box list bento/ubuntu-18.04 (virtualbox, 202112.19.0) bento/ubuntu-20.04 (virtualbox, 202112.19.0) bento/ubuntu-20.04 (virtualbox, 202206.03.0) generic/ubuntu1604 (virtualbox, 4.1.6) generic/ubuntu1804 (virtualbox, 4.1.6) generic/ubuntu2004 (virtualbox, 4.1.6) ubuntu/focal64 (virtualbox, 20220825.0.0) PS D:\RCC-sharing\vagrant-demo\docker-install> vagrant init bento/ubuntu-20.04 --box-version 202206.03.0 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.

本次所使用的 Vagrantfile

Vagrant.configure("2") do |config| config.vm.box = "bento/ubuntu-20.04" config.vm.box_version = "202206.03.0" config.vm.hostname = 'docker-lab' config.vm.define vm_name = 'dockerlab' config.vm.provider "virtualbox" do |vb| # Customize the amount of memory on the VM: vb.cpus = 2 vb.memory = "2048" end # Enable provisioning with a shell script. Additional provisioners such as # Ansible, Chef, Docker, Puppet and Salt are also available. Please see the # documentation for more information about their specific syntax and use. config.vm.provision "shell", inline: <<-SHELL # Uninstall old versions sudo apt-get remove docker docker-engine docker.io containerd runc # Install using the repository sudo apt-get update sudo apt-get -y install \ ca-certificates \ curl \ gnupg \ lsb-release sudo mkdir -p /etc/apt/keyrings curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg echo \ "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \ $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null sudo apt-get update sudo apt-get install docker-ce docker-ce-cli containerd.io docker-compose-plugin -y apt-cache madison docker-ce SHELL end

05. Docker 簡易操作

  1. 驗證 Docker 已經透過 Vagrantfile 在啟動虛擬機後,使用 inline: <<-SHELL 完成安裝
vagrant@docker-lab:~$ sudo docker version Client: Docker Engine - Community Version: 20.10.17 API version: 1.41 Go version: go1.17.11 Git commit: 100c701 Built: Mon Jun 6 23:02:57 2022 OS/Arch: linux/amd64 Context: default Experimental: true Server: Docker Engine - Community Engine: Version: 20.10.17 API version: 1.41 (minimum version 1.12) Go version: go1.17.11 Git commit: a89b842 Built: Mon Jun 6 23:01:03 2022 OS/Arch: linux/amd64 Experimental: false containerd: Version: 1.6.8 GitCommit: 9cd3357b7fd7218e4aec3eae239db1f68a5a6ec6 runc: Version: 1.1.4 GitCommit: v1.1.4-0-g5fd4c4d docker-init: Version: 0.19.0 GitCommit: de40ad0
  1. 運行 Container docker run
    下載測試映像檔 (hello-world) 並在 Container 中運行,print 出訊息後退出(Exited) Container。
vagrant@docker-lab:~$ sudo docker run hello-world Unable to find image 'hello-world:latest' locally latest: Pulling from library/hello-world 2db29710123e: Pull complete Digest: sha256:7d246653d0511db2a6b2e0436cfd0e52ac8c066000264b3ce63331ac66dca625 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/
  1. 列出容器
    • 運行中 docker ps
    • 所有容器 (運行中-Up & 非運行中-Exited) docker ps -a
vagrant@docker-lab:~$ sudo docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES vagrant@docker-lab:~$ sudo docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 6c800baf4a7d hello-world "/hello" 48 seconds ago Exited (0) 46 seconds ago clever_keldysh
  1. 安裝 NGINX 網頁伺服器
    • 由於執行完 NGINX 會退出 Container,因此可以加入 Option -d 在背景繼續執行
    • -p 80:80 將 Guest OS 的 80 port 路由到 Container 的 80 port
vagrant@docker-lab:~$ sudo docker run -p 80:80 nginx Unable to find image 'nginx:latest' locally latest: Pulling from library/nginx 7a6db449b51b: Pull complete ca1981974b58: Pull complete d4019c921e20: Pull complete 7cb804d746d4: Pull complete e7a561826262: Pull complete 7247f6e5c182: Pull complete Digest: sha256:b95a99feebf7797479e0c5eb5ec0bdfa5d9f504bc94da550c2f58e839ea6914f Status: Downloaded newer image for nginx:latest /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration /docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/ /docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh 10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf 10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf /docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh /docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh /docker-entrypoint.sh: Configuration complete; ready for start up 2022/09/03 06:45:59 [notice] 1#1: using the "epoll" event method 2022/09/03 06:45:59 [notice] 1#1: nginx/1.23.1 2022/09/03 06:45:59 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6) 2022/09/03 06:45:59 [notice] 1#1: OS: Linux 5.4.0-110-generic 2022/09/03 06:45:59 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576 2022/09/03 06:45:59 [notice] 1#1: start worker processes 2022/09/03 06:45:59 [notice] 1#1: start worker process 30 2022/09/03 06:45:59 [notice] 1#1: start worker process 31 172.17.0.1 - - [03/Sep/2022:06:46:07 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.68.0" "-" 10.0.2.2 - - [03/Sep/2022:06:46:21 +0000] "GET / HTTP/1.1" 200 615 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36" "-" 2022/09/03 06:46:21 [error] 31#31: *2 open() "/usr/share/nginx/html/favicon.ico" failed (2: No such file or directory), client: 10.0.2.2, server: localhost, request: "GET /favicon.ico HTTP/1.1", host: "127.0.0.1:8080", referrer: "http://127.0.0.1:8080/" 10.0.2.2 - - [03/Sep/2022:06:46:21 +0000] "GET /favicon.ico HTTP/1.1" 404 555 "http://127.0.0.1:8080/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36" "-" ^C2022/09/03 06:46:33 [notice] 1#1: signal 2 (SIGINT) received, exiting 2022/09/03 06:46:33 [notice] 30#30: exiting 2022/09/03 06:46:33 [notice] 30#30: exit 2022/09/03 06:46:33 [notice] 31#31: exiting 2022/09/03 06:46:33 [notice] 31#31: exit 2022/09/03 06:46:33 [notice] 1#1: signal 17 (SIGCHLD) received from 31 2022/09/03 06:46:33 [notice] 1#1: worker process 31 exited with code 0 2022/09/03 06:46:33 [notice] 1#1: signal 29 (SIGIO) received 2022/09/03 06:46:33 [notice] 1#1: signal 17 (SIGCHLD) received from 30 2022/09/03 06:46:33 [notice] 1#1: worker process 30 exited with code 0 2022/09/03 06:46:33 [notice] 1#1: exit
  • 驗證 NGINX 服務
vagrant@docker-lab:~$ curl 127.0.0.1:80 <!DOCTYPE html> <html> <head> <title>Welcome to nginx!</title> <style> html { color-scheme: light dark; } body { width: 35em; margin: 0 auto; font-family: Tahoma, Verdana, Arial, sans-serif; } </style> </head> <body> <h1>Welcome to nginx!</h1> <p>If you see this page, the nginx web server is successfully installed and working. Further configuration is required.</p> <p>For online documentation and support please refer to <a href="http://nginx.org/">nginx.org</a>.<br/> Commercial support is available at <a href="http://nginx.com/">nginx.com</a>.</p> <p><em>Thank you for using nginx.</em></p> </body> </html>
  • 使用 localhost 的瀏覽器訪問 NGINX Container

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
探討為何在 Localhost 要使用 8080 port 訪問 NGINX?

  1. 移除 NGINX Container 及 Image
    • 列出運行中的 Container docker ps
    • 列出所有的 Container docker ps -a
    • 刪除所有的 Container 才能成功移除對應的 Image
vagrant@docker-lab:~$ sudo docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES vagrant@docker-lab:~$ sudo docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES f715b3fce5b3 nginx "/docker-entrypoint.…" 12 seconds ago Exited (0) 9 seconds ago affectionate_chatterjee 6c800baf4a7d hello-world "/hello" About an hour ago Exited (0) About an hour ago clever_keldysh vagrant@docker-lab:~$ sudo docker images REPOSITORY TAG IMAGE ID CREATED SIZE nginx latest 2b7d6430f78d 11 days ago 142MB hello-world latest feb5d9fea6a5 11 months ago 13.3kB vagrant@docker-lab:~$ sudo docker rmi 2b7d6430f78d Error response from daemon: conflict: unable to delete 2b7d6430f78d (must be forced) - image is being used by stopped container f715b3fce5b3 vagrant@docker-lab:~$ sudo docker container rm f715b3fce5b3 f715b3fce5b3 vagrant@docker-lab:~$ sudo docker rmi 2b7d6430f78d Untagged: nginx:latest Untagged: nginx@sha256:b95a99feebf7797479e0c5eb5ec0bdfa5d9f504bc94da550c2f58e839ea6914f Deleted: sha256:2b7d6430f78d432f89109b29d88d4c36c868cdbf15dc31d2132ceaa02b993763 Deleted: sha256:83cfe7b2ae78dff709b878ea6827c2b7447910f22f5c18d2155bc4ee678b6589 Deleted: sha256:8354a3628193232756e7e39423937a89bdea9738fcd033e3009c34847d44f1cc Deleted: sha256:edd004a0175251a1fa027a4949079439eb989b9c9d0dc863c2c834e0da69ed2e Deleted: sha256:e65b26350d575233ec4815a0ced147030bb9db419084e6a1561aab8c9f05f20e Deleted: sha256:d75805fc21788b744c171b7ca303a153b34b61b61401c74348b0a16c9bfabbc8 Deleted: sha256:6485bed636274e42b47028c43ad5f9c036dd7cf2b40194bd556ddad2a98eea63 vagrant@docker-lab:~$ sudo docker images REPOSITORY TAG IMAGE ID CREATED SIZE hello-world latest feb5d9fea6a5 11 months ago 13.3kB