Docker学習 - はじめはhello-worldをdocker runしよう

2020年2月20日Docker

Dockerをインストールしたら、動作確認のために実行してみるhello-worldですが、はじめてDockerを実行するときはコマンドもよくわからないものです。

とりあえずDockerで何かを動かしてみたくなりますよね。

さくっとhello-worldを実行する手順についてまとめてみました。

Dockerをインストールする

まずは、Dockerをインストールインストールしましょう。

AWSのEC2にインストールするもよし、ローカルのPCにインストールするのもいいですが、私はDockerの開発環境はWindowsのWSL2でUbutntuを入れてその上にDockerをしました。

WSL2のUbuntuにインストールしてみよう!という方は以下の記事を参考にインストールしてみてください。

Dockerのサービスを立ち上げる

Dockerサービスを起動するために以下のコマンドを実行しましょう。

$ sudo systemctl start docker

または

$ sudo service docker start
注意

WSL2のUbuntuの場合はsystemctlが利用できないという制限があります。
この制限が早く解消されるといいですね。

WSL2でsystemctlが利用できる方法がわかりました。以下の記事を参考にして下さい。

Dockerサービスが起動しているかは、以下のコマンドで確認できます。

$ sudo service docker status
 * Docker is running

次回から自動起動にする場合は以下のコマンドで設定できます。

$ sudo systemctl enable docker

hello-worldのDockerイメージをpullする

Dockerサービスが起動しましたので、次にDocker Hubからhello-worldのイメージを取得します。

難しく感じるかもしれませんが、コマンドは単純です。

$ docker pull hello-world
Using default tag: latest
latest: Pulling from library/hello-world
1b930d010525: Pull complete
Digest: sha256:9572f7cdcee8591948c2963463447a53466950b3fc15a247fcad1917ca215a2f
Status: Downloaded newer image for hello-world:latest

特にエラーが出ていなければ成功していますが、以下のコマンドでhello-worldのDockerイメージが取得できたか確認しましょう

$ docker image ls
REPOSITORY                 TAG                 IMAGE ID            CREATED             SIZE
hello-world                latest              fce289e99eb9        13 months ago       1.84kB

Dockerイメージの一覧を確認するコマンドです。

左から

  • リポジトリ名(Dockerイメージ名)
  • タグ(バージョン) ※latestは最新バージョンのことです
  • イメージID
  • 作成日
  • サイズ

です。

docker run コマンドでhello-worldを実行

docker run には色々とオプションがありますが、hello-worldは特にオプションなど気にせず実行してみましょう。

$ docker run hello-world

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 Hubのhello-worldのページの「Example output」にも同じ結果が出力されているのが確認できます。

 

いかがでしたか、Dockerの仕組みを理解してから始めるのもよいですが、まずは動かしてみると達成感がありますよね。

次回はnginxのDockerイメージを起動してブラウザから確認してみたいと思います。

Docker

Posted by snow