【手順系】vagrant+dockerを使ったWebアプリケーション開発①:開発環境構築と「Hello World!」

本noteの概要

仮想環境上でのWebアプリケーション開発を行うため、Vagrantfileに必要なコードを記載し、vagrant upコマンドで仮想環境を構築する。

本noteの対象者

VirtualBoxおよびVagrantをインストールしている方
docker hubのアカウントを開設している方

本noteの環境

PC環境(ホスト)

# OSのバージョン
(base) $ sw_vers
ProductName:    Mac OS X
ProductVersion: 10.14.6
BuildVersion:   18G2022

# Virtualboxのバージョン
(base) $ VBoxManage -v
6.1.2r135662

# vagrantのバージョン
(base) $ vagrant -v
Vagrant 2.2.7

Today's Thema:vagrant+dockerによる開発環境構築

完成図

<最終的なディレクトリ構成>
▼ ホスト(ローカル)

- ops # 今後のアプリケーション開発でソースを管理するための空のディレクトリ     
- Vagrantfile   

▼ ゲスト(仮想環境)

- srv   
 - ops   

1.仮想環境情報の設定

vagrant initコマンドでVagrantfileを作成し、Vagrantfileに環境構築のために必要な設定を記述します。

⑴ Vagrantfileの作成(vagrant 初期化)

(base) $ mkdir vagrant-docker && cd vagrant-docker # 適当なディレクトリを作成し、作成したディレクトリへ移動
(base) :vagrant-docker $ vagrant init ubuntu/xenial64 # vagrant 初期化

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を使った仮想環境情報設定

<vagrantfile>

$install_docker = <<SCRIPT
sudo apt-get -y install apt-transport-https ca-certificates curl software-properties-common
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
sudo apt-get update
sudo apt-get -y install docker-ce
sudo systemctl start docker
sudo curl -L "https://github.com/docker/compose/releases/download/1.23.1/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
docker-compose --version
SCRIPT

Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/xenial64"
  config.vm.network "forwarded_port", guest: 80, host: 8080 # localhostと仮想環境をつなげるための設定
  config.vm.synced_folder 'ops/', '/srv/ops'
  config.vm.provision 'shell', inline: $install_docker
end

ソースコードを管理するディレクトリの作成

今後、アプリケーション開発を行う際のソースコードを管理するディレクトリを作成。

(base) :vagrant-docker $ mkdir ops

2.仮想環境の起動・接続

⑴ 仮想環境の起動

(base) :vagrant-docker $ vagrant up

Bringing machine 'default' up with 'virtualbox' provider...
==> default: Box 'centos/7' could not be found. Attempting to find and install...
    default: Box Provider: virtualbox
    default: Box Version: >= 0

〜中略〜

    default: docker-compose version 1.23.1, build b02f1306

⑵ 仮想環境への接続

(base) :vagrant-docker $ vagrant ssh

Welcome to Ubuntu 16.04.6 LTS (GNU/Linux 4.4.0-173-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage


17 packages can be updated.
16 updates are security updates.

New release '18.04.4 LTS' available.
Run 'do-release-upgrade' to upgrade to it.

vagrant@ubuntu-xenial:~$

3.仮想環境のセットアップ状況確認

⑴ ゲストOSのバージョン確認

# Linuxのバージョンが記載されているファイルを検索
vagrant@ubuntu-xenial:~$ ls /etc/*-release
/etc/lsb-release  /etc/os-release

# ゲストOSのバージョンを出力
vagrant@ubuntu-xenial:~$ cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=16.04
DISTRIB_CODENAME=xenial
DISTRIB_DESCRIPTION="Ubuntu 16.04.6 LTS"

⑵ dockerのインストール確認

vagrant@ubuntu-xenial:~$ docker version
Client: Docker Engine - Community
 Version:           19.03.6
 API version:       1.40
 Go version:        go1.12.16
 Git commit:        369ce74a3c
 Built:             Thu Feb 13 01:28:06 2020
 OS/Arch:           linux/amd64
 Experimental:      false
Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.40/version: dial unix /var/run/docker.sock: connect: permission denied

⑶ docker-composeのインストール確認

vagrant@ubuntu-xenial:~$ docker-compose version
docker-compose version 1.23.1, build b02f1306
docker-py version: 3.5.0
CPython version: 3.6.7
OpenSSL version: OpenSSL 1.1.0f  25 May 2017

4.Dockerコンテナを使った「Hello World!」

⑴ Webアプリケーション動作確認用コンテナ(training/webapp)の起動
vagrant@ubuntu-xenial:~$ sudo docker run -d -p 80:5000 training/webapp python app.py
Unable to find image 'training/webapp:latest' locally
latest: Pulling from training/webapp
Image docker.io/training/webapp:latest uses outdated schema1 manifest format. Please upgrade to a schema2 image for better future compatibility. More information at https://docs.docker.com/registry/spec/deprecated-schema-v1/
e190868d63f8: Pull complete 
909cd34c6fd7: Pull complete 
0b9bfabab7c1: Pull complete 
a3ed95caeb02: Pull complete 
10bbbc0fc0ff: Pull complete 
fca59b508e9f: Pull complete 
e7ae2541b15b: Pull complete 
9dd97ef58ce9: Pull complete 
a4c1b0cb7af7: Pull complete 
Digest: sha256:06e9c1983bd6d5db5fba376ccd63bfa529e8d02f23d5079b8f74a616308fb11d
Status: Downloaded newer image for training/webapp:latest
1eb795fd41625fb81974d2a54a66e39329f535fc9a664bcb5e21c2cb9ce4f4ce
⑵ ブラウザ上での表示確認

http://localhost:8080/

f:id:otsuba1:20200213181854p:plain

※起動したコンテナは後述のdocker stopコマンドで停止できます。

5.仮想環境やdocker関連コマンド

○ 起動中コンテナの一覧表示
vagrant@ubuntu-xenial:~$ sudo docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                  NAMES
1eb795fd4162        training/webapp     "python app.py"     19 minutes ago      Up 19 minutes       0.0.0.0:80->5000/tcp   gallant_murdock

※ 停止中のコンテナも含める場合はsudo docker ps -aコマンドを使用

○ 起動中コンテナへのログイン
vagrant@ubuntu-xenial:~$ sudo docker exec -it 1eb795fd4162 /bin/bash
root@1eb795fd4162:/opt/webapp# 

【参考】今回使用した動作確認用コンテナの中身について
上記のコマンドで起動中コンテナにログインし、lsコマンドを入力するとコンテナ内のコンテンツを確認することが可能。

root@1eb795fd4162:/opt/webapp# ls
Procfile  app.py  requirements.txt  tests.py

またvi app.pyコマンドでファイルの中身を確認すると、今回のアプリケーションはPython(Flask)で書かれていることがわかります。

<app.py>

import os

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    provider = str(os.environ.get('PROVIDER', 'world'))
    return 'Hello '+provider+'!'

if __name__ == '__main__':
    # Bind to PORT if defined, otherwise default to 5000.
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)
○ 起動しているDockerコンテナの停止
vagrant@ubuntu-xenial:~$ sudo docker stop 1c763df10ac5
○ 仮想環境からのログアウト
vagrant@ubuntu-xenial:~$ exit
○ 仮想環境の停止
(base) :vagrant-docker $ vagrant halt
==> default: Attempting graceful shutdown of VM...
○ 仮想環境の稼働状況確認
(base) $ vagrant global-status
id       name     provider   state    directory                                   
----------------------------------------------------------------------------------
48dd523  default  virtualbox running  /Users/vm/infra                     
6126d9b  main     virtualbox running  /Users/vm/ubuntu                    
2911deb  minikube virtualbox poweroff /Users/vm/Linux/vagrant-minikube               
 
The above shows information about all known Vagrant environments
on this machine. This data is cached and may not be completely
up-to-date (use "vagrant global-status --prune" to prune invalid
entries). To interact with any of the machines, you can go to that
directory and run Vagrant, or you can use the ID directly with
Vagrant commands from any directory. For example:
"vagrant destroy 1a2b3c4d"
○ 仮想環境の削除
(base) $ vagrant destroy 48dd523

【参考】
Vagrant+VirtualBoxによるDocker環境構築 - Qiita
Vagrantの使い方 - Qiita
Dockerインストールメモ - Qiita
【まとめ】Vagrant コマンド一覧 - Qiita
VagrantとDockerで「環境に縛られない」開発環境を構築しよう - RAKUS Developers Blog | ラクス エンジニアブログ