第4 : Dockerfileについて

第4 : Dockerfileについて 参考:https://knowledge.sakura.ad.jp/15253/

Tomcatをホスト側にダウンロード (※ver 10.1.1)

サイトでtomcatjreのバージョンを確認する

サイト:https://tomcat.apache.org/tomcat-10.1-doc/setup.html

→tomcat10はjreが11以上

tomcatダウンロード

$ curl -OL http://www-eu.apache.org/dist/tomcat/tomcat-10/v10.1.1/bin/apache-tomcat-10.1.1.tar.gz

移動

$ mkdir -p files
$ mv ./apache-tomcat-10.1.1.tar.gz ./files 

Dockerfileを使用して、Dockerイメージを作成

Dockerfile作成

サイトのままだとバージョンが古い&バージョン違いでエラーが出るので、以下に変更した。

FROM centos:7
RUN yum install -y java-11
ADD files/apache-tomcat-10.1.1.tar.gz /opt/
CMD [ "/opt/apache-tomcat-10.1.1/bin/catalina.sh", "run" ]

バージョンは、
tomcat:10.1.1
centos:7
java:11.0

Dockerビルド実行

Dockerイメージを作成するコマンド
TomcatのDockerイメージが作成できる

$ docker build -t tomcat:1 .
  // 略
Use 'docker scan' to run Snyk tests against images to find vulnerabilities and learn how to fix them

% docker images
REPOSITORY   TAG       IMAGE ID       CREATED         SIZE
tomcat       1         d5ab17ea190e   2 minutes ago   577MB

「-t」はイメージのタグ付けオプション
作成されるイメージに対してタグ付けられる
名前とオプションでタグを 「名前:タグ」 の形式で指定

リポジトリ名 → tomcat タグ → 1

参考:https://docs.docker.jp/engine/reference/commandline/build.html#t
参考:https://docs.docker.jp/engine/reference/commandline/tag.html

書き方は以下のようになる

docker build -t <Dockerイメージ名> <Dockerfileが存在するディレクトリ>

コンテナ起動

% docker run -it -d --name tomcat-1 -p 8081:8080 tomcat:1
3742a78a65c18904ad15b038ada35b05861e1ef1b5ff3323257b9c5e2eb45bf8

確認

% docker ps
CONTAINER ID   IMAGE      COMMAND                  CREATED         STATUS         PORTS                    NAMES
3742a78a65c1   tomcat:1   "/opt/apache-tomcat-…"   5 seconds ago   Up 4 seconds   0.0.0.0:8081->8080/tcp   tomcat-1

ページ確認

ブラウザで以下を入れて表示確認

http://localhost:8081/

log確認

$ docker logs -f tomcat-1

書き方は以下

docker logs [OPTIONS] CONTAINER

「-f」オプション: 「--follow」の略
出力をフォローし続ける(表示し続ける)

tomcat-1」: コンテナ名
docker psで「NAMES」の欄に出てくる

参考:https://docs.docker.jp/engine/reference/commandline/logs.html

Dockerfileを書く際のポイントや嵌りどころ、注意点について

毎回コンテナを起動

・dockerコマンドごとに新しく起動したコンテナで実行されるので、次の行が前の行のコマンドを継承していない。
・コマンドを続けて書きたい時は、「&&」で連結させ使用する(シェルと同じように)
・たとえば以下、test.txtは/tmpに作成されない。

RUN cd /tmp           # ⑤
RUN touch test.txt    # ⑥

キャッシュを意識

・被る部分、似たような部分は最初の方に書いておく ・ex ) Dockerfile_2

FROM centos:7
RUN yum install -y java-11
RUN touch /tmp/test.txt
ADD files/apache-tomcat-10.1.1.tar.gz /opt/
CMD ["/opt/apache-tomcat-10.1.1/bin/catalina.sh", "run"]

これをビルドすると

% docker build -t tomcat:2 -f Dockerfile_2 .
[+] Building 1.3s (9/9) FINISHED                                                                                                                     
 => [internal] load build definition from Dockerfile_2                                                                                          0.0s
 => => transferring dockerfile: 39B                                                                                                             0.0s
 => [internal] load .dockerignore                                                                                                               0.0s
 => => transferring context: 2B                                                                                                                 0.0s
 => [internal] load metadata for docker.io/library/centos:7                                                                                     1.2s
 => [1/4] FROM docker.io/library/centos:7@sha256:c73f515d06b0fa07bb18d8202035e739a494ce760aa73129f60f4bf2bd22b407                               0.0s
 => [internal] load build context                                                                                                               0.0s
 => => transferring context: 82B                                                                                                                0.0s
 => CACHED [2/4] RUN yum install -y java-11                                                                                                     0.0s
 => CACHED [3/4] RUN touch /tmp/test.txt                                                                                                        0.0s
 => CACHED [4/4] ADD files/apache-tomcat-10.1.1.tar.gz /opt/                                                                                    0.0s
 => exporting to image                                                                                                                          0.0s
 => => exporting layers                                                                                                                         0.0s
 => => writing image sha256:fa40a923c1092c078ed002e6aeb6e5bbe6d3d715ad4badbf3fbd2cb0f209dad3                                                    0.0s
 => => naming to docker.io/library/tomcat:2                                                                                                     0.0s

Use 'docker scan' to run Snyk tests against images to find vulnerabilities and learn how to fix them

変更がない部分は、以前作成されたレイヤー(中間的なDockerイメージ)が使用されるため、Dockerビルドの処理時間が短くなる。
そのため、コマンドの実行順序を意識してDockerfileを書くとよい

なるべくまとめて実行

・Dockerfileの各コマンドごとにレイヤーが作成されるので、その分Dockerイメージのサイズが大きくなる。そのため、なるべく1コマンドで実行できるものは、まとめて実行する
・作成できるレイヤーには上限(128レイヤー)がある

Dockerfileを使うことの利点

Infrastructure as Code (IaC)、CI/CD

Dockerイメージの管理

【ポートフォリオ】Bootstrapの素材を配置【企業HP】

  1. hostsに以下を追加
127.0.0.1 company
  1. httpd-vhosts.confに以下を追加
##company
<VirtualHost *:80>
DocumentRoot "C:\Users\myuser\Desktop\workspace\company"
ServerName company
</VirtualHost>

<Directory "C:\Users\myuser\Desktop\workspace\company">
AllowOverride All
Require all granted
</Directory>
  1. 以下から「Download」を押しダウンロード
    Elearning – Free Bootstrap 5 CSS3 Education Website Template

  2. 以下に配置

C:\Users\myuser\Desktop\workspace\company
  1. XAMPP起動

Boostrapの使い方

こんな感じ

<!DOCTYPE html>
<html lang="jp">
<head>
    <meta charset="utf-8">
    <title>お問い合わせフォーム</title>
    <!-- GoogleFontsのタグ 「Use on the web」 -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Reggae+One&display=swap" rel="stylesheet">
    <!-- これはBoostrapのタグ -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <!-- GoogleFontsのタグ 「CSS rules to specify families」 -->
    <style>
        body {
            background: #f3f3f3;
            font-family: 'Reggae One', cursive;
        }
    </style>
</head>
<body>
<div class="container mt-5 pt-5">
    <div class="row">
        <div class="col-md-6 offset-md-3">
            <h3 class="mb-5 text-center">お問い合わせ</h3>
            <form method="post">
                <div class="mb-3">
                    <input type="text" class="form-control" name="name" placeholder="お名前" value="">
                </div>
                <div class="mb-3">
                    <input type="text" class="form-control" name="email" placeholder="メールアドレス" value="">
                </div>
                <div class="mb-3">
                    <input type="text" class="form-control" name="subject" placeholder="件名" value="">
                </div>
                <div class="mb-4">
                    <textarea class="form-control" name="message" rows="5" placeholder="本文"></textarea>
                </div>
                <div class="d-grid">
                    <button type="submit" class="btn btn-success">送信</button>
                </div>
            </form>
        </div>
    </div>
</div>
</body>
</html>

参考

codeforfun.jp

【PHP環境】composerインストール

  1. XAMPPを入れておく
  2. ダウンロード ここからexeをダウンロード
  3. インストール

*composerはphpがないと動かない

参考 ダウンロードのチェックについて書かれているページ freelance.levtech.jp

composerについて getcomposer.org

Windowsの開発環境

1. git for windows

1-1. ここからインストール

Git for Windows

1-2. 環境変数に設定
1-3. メールアドレス、ユーザ名を設定
git config --global user.name "ユーザー名"
git config --global user.email "メールアドレス"
git config --global core.quotepath false #日本語ファイル名がエスケープされないように

登録されてるか確認

$ git config --list

user.name=[先ほど設定したユーザ名]
user.email=[先ほど設定したメールアドレス]

2. Visual Studio Code

2-1. ここからインストール

Visual Studio Code – コード エディター | Microsoft Azure

2-2. terminalに設定する

ファイル→ユーザー設定→設定
setting.jsonを以下のように記載

{
    "workbench.colorTheme": "Visual Studio Light",
    "editor.fontWeight": 800,
    "[json]": {

        "editor.quickSuggestions": {
            "strings": true
        },
        "editor.suggest.insertMode": "replace"
    },
    "php.validate.executablePath": "C:\\xampp\\php\\php.exe",
    "terminal.external.windowsExec": "C:\\Program Files\\Git\\git-bash.exe",
    "terminal.integrated.defaultProfile.windows": "Git Bash",
    "window.zoomLevel": 1
}

3. 鍵作成

ディレクトリ作成

mkdir .ssh

権限変更

chmod 700 .ssh/

作成したディレクトリに移動

cd .ssh

鍵を作成します。下記がでたらEnterキーを押す

$ ssh-keygen -t rsa -b 4096 -C "<自分のGitHubメールアドレス>"
> Generating public/private rsa key pair.

パスフレーズを入力

> Enter a file in which to save the key (/home/<user>/.ssh/id_rsa): [Press enter]

もう一度入力

> Enter passphrase (empty for no passphrase): 
> Enter same passphrase again:

下記のような表示がでたら作成完了

Your identification has been saved in /home/username/.ssh/id_rsa.
Your public key has been saved in /home/username/.ssh/id_rsa.pub.
The key fingerprint is:SHA256:sawrngnbieBhebKbfueKUBEbuget,
The key's randomart image is:
+---[RSA 4096]----+
|    -A_O.   .    |
|   ..A. =        |
|    oB=O*        |
|   o. =  o       |
|    *...A -      ||   = - A C       ||  DD o o        |
|   P-A .         |
| .A...           |
+----[SHA256]-----+

~/.sshディレクトリ配下に公開鍵id_rsa.pubと秘密鍵id_rsaのファイルが作成されていることが確認する

$ ls -al ~/.ssh
id_rsa id_rsa.pub

ssh-agentを開始

$ eval "$(ssh-agent -s)"

SSH秘密鍵ssh-agentに追加

$ ssh-add ~/.ssh/id_rsa

4.github

4-1. githubに鍵を登録

5. 接続設定

5-1. configファイル作成

ファイル生成

touch ~/.ssh/config

中身に以下を貼り付け

Host github
HostName github.com
IdentityFile ~/.ssh/id_rsa
User git

6. 接続確認

$ ssh -T git@github.com
Hi TechsReport! You've successfully authenticated, but GitHub does not provide shell access.

7. XAMPP

7-1. インストール
7-2. 作業ディレクトリとテストファイルを作成

下記のようにhtmlファイルを作成する

C:\Users\<username>\Desktop\work\test001\index.html
<!DOCTYPE html>
Hello
</html>
7-3. バーチャルホストを有効にする

下記を開く
(念のためバックアップを取っておくこと)

C:\xampp\apache\conf\httpd.conf

521行目あたりに「httpd-vhosts.conf」とあるので、先頭の「#」を外す
これで有効化となる

# Virtual hosts
#Include conf/extra/httpd-vhosts.conf
# Virtual hosts
Include conf/extra/httpd-vhosts.conf
7-4. ドキュメントルートの設定

下記を開く
(念のためバックアップをとっておく)

C:\xampp\apache\conf\extra\httpd-vhosts.conf

20行目あたりの「##」を外す

##NameVirtualHost *:80

バーチャルホスト以外を拒否する場合は下記を追記する

<VirtualHost _default_:80>
    ServerName any
    <Location />
        Require all denied
    </Location>
</VirtualHost>

下記を参考に作業ディレクトリを追加して上書きする

<VirtualHost *:80>
DocumentRoot "C:\Users\<username>\Desktop\work\test001"
ServerName myhost
</VirtualHost>

<Directory "C:\Users\<username>\Desktop\work\test001">
AllowOverride All
Require all granted
</Directory>
7-5. サーバーネームの設定

下記のファイルを開く
(念のためバックアップを取っておく)

C:\Windows\System32\drivers\etc\hosts

一番に下記を追加する
(「myhost」はhttpd-vhostsの「ServerName」で記載したものを指定する)

127.0.0.1 myhost
7-5. XAMPPを再起動する

設定ファイル編集後は、必ずXAMPPを再起動させる必要がある

7-6. webサイトを確認

XAMPPで「start」を押し起動後ブラウザで以下を開く
(「myhost」はhostsで記載したものを指定)

http://myhost

参考サイト

yu-report.com

bsj-k.com

macoblog.com