docker for beginners

はじめに

この記事では、docker for beginersを実行していきます。

必要な事前準備はDockerのインストールのみです!

入門

コンピュータのセットアップ

下記のコマンドを実行してDockerを正しくインストールできているか確認します。

1
docker run hello-world

以下のようなメッセージが表示されれば成功です。少し時間がかかる場合があります。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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/

イメージhello-worldをからコンテナを生成して起動しています。初回実行時は、イメージが存在しないためレジストリからイメージを自動でダウンロードしています。

Hello World

Busyboxで遊ぶ

イメージbusyboxをダウンロードします。

1
docker pull busybox

下記のコマンドでホスト上にあるイメージの一覧を確認できます。

1
docker images

Docker Run

イメージからコンテナを作成し、実行してみます。

1
docker run busybox

一見、何も起きなかったように見えますが、コンテナが起動し空のコマンドを実行してから終了しました。

次のようにすると、コンテナ上でコマンドを実行してから終了します。

1
docker run busybox echo "hello from busybox"

次のコマンドで起動中のコンテナを確認できます。

1
docker ps

先ほど実行したコンテナはすでに終了しているので、このコマンドでは確認できません。
終了したコンテナも含めて確認するには以下のコマンドを実行します。

1
docker ps -a

Dockerを利用したWebアプリケーション

静的サイト

デモ用に作成されたWebサイトを起動します。

1
docker run --rm prakhar1989/static-site

--rmオプションをつけることで、コンテナ終了時に自動でコンテナを削除することができます。

さて、実はこれではポートの割り当てをしていないためWebサイトにアクセスすることができません。
Ctrl+C等で、一旦終了して実行方法を変えてみましょう。

  • ターミナルが実行中のコンテナに接続されないようにする
  • コンテナに名前をつける
  • (ランダムに)ポートを割り当てる
1
docker run -d -P --name static-site prakhar1989/static-site

これでhttp://localhost[PORT]でアクセすることができます。

以下のようにポートを指定することも可能です。

1
docker run -p 8888:80 prakhar1989/static-site

以下のコマンドでコンテナを停止することができます。--rmオプションで起動していた場合は、同時に削除されます。

1
docker stop static-site

Docker Iamges

ローカルで使用可能なDockerのイメージ一覧を確認します。

1
docker images

docker pullする際に、タグ(バージョン)を指定することができます。

1
docker pull ubuntu:18.04

初めてのイメージ

次に自分でイメージを作成します。

1
2
git clone https://github.com/prakhar1989/docker-curriculum.git
cd docker-curriculum/flask-app

Dockerfile

Dockerfileを作成します。

1
vi Dockerfile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
FROM python:3

# set a directory for the app
WORKDIR /usr/src/app

# copy all the files to the container
COPY . .

# install dependencies
RUN pip install --no-cache-dir -r requirements.txt

# define the port number the container should expose
EXPOSE 5000

# run the command
CMD ["python", "./app.py"]
1
docker build -t yourusername/catnip .

記事情報

  • 投稿日:2020年6月15日
  • 最終更新日:2020年7月4日