0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Docker学習記録-03

Last updated at Posted at 2025-11-10

今回はだいぶ難しくなりそうな第5章(Chapter5)からやってみようと思う。

1 Dockerfileの作成とBuildの練習
5-1でも5-2でもほとんど同じなので5-2から実施する。

Dockerfile
FROM ubuntu:latest
RUN apt-get update && apt-get install -y nginx

build(コンパイル)するときは[docker buid . -t タグ名]

コマンド
docuker build . -t docker5-2

実行するとこんな感じ(家の環境では1分ぐらいかかった)
image.png

dokcer image lsで確認すると新しいイメージ(doker5-2)が出来ている
image.png

imageを削除する場合はdocker image rm イメージ名

コマンド
docker image rm docker5-2

ここではイメージの作成と削除の実行まで

2 Dockerfileの完成から起動まで
5-3,5-4とコマンドの追加、ファイルの追加等を実施して最終的にDockerfileは以下のような形になる。(まあubuntuでnginxを立ち上げただけですが)

Dockerfile
FROM ubuntu:latest
RUN apt-get update && apt-get install -y nginx
# ローカルの index.html を Nginx の公開ディレクトリにコピー
ADD index.html /var/www/html/
# コンテナがフォアグラウンドで動作するように設定
CMD ["nginx", "-g", "daemon off;"]

カレントディレクトリに適当なindex.htmlを作成してから以下を実行するとコンテナが作成され、Webページを見ることが出来るようになる。

コマンド
# imageの作成
docker build . -t docker5-4
# 実行
docker run -d -p 8080:80 docker5-4

ポート使用中のエラーが出る場合は前に立ち上げたコンテナがそのまま残っている場合があるのでdocker ps -aで確認してからdocker stopで止めておく。動作確認が終了したらコンテナの停止、削除、イメージの削除を行っておく。

※〇〇ページを見て実行しておく・・・だと初見ではツラいかも
※一応以下に実行例を載せておく

コマンド例(実験後のお掃除)
# コンテナの確認
docker ps -a
CONTAINER ID   IMAGE   (省略)     PORTS      NAMES
4ead94930702   docker5-4   0.0.0.0:8080->80/tcp sleepy_man
#コンテナID(4ead94930702)か自動的に付いた名前(sleepy_man)で停止と削除
docker stop 4ead94930702
docker rm 4ead94930702
# 合わせてイメージも確認と削除(コンテナの場合と同様にイメージIDを確認)
docker image ls
docker image rm xxxxxx

ここから先がちょっと駆け足なので、ちょっと回り道をしてこのDockerfileを活用するdocker-compose.yamlを作成してみる

■補足:docker-compose.yaml
生成AIにこのDockerfileを活用したdocker-composeの例を尋ねたら以下のような例を示した

docker-compose.yaml
services:
  web:
    build: .
    container_name: mynginx
    ports:
      - "8080:80"       # ポートマッピング
    volumes:
      - ./index.html:/var/www/html/index.html  # index.htmlの反映
    restart: unless-stopped    # 自動再起動設定

コマンド1つでbuildからrunまでやってくれるので確かに便利だ

起動と停止
docker compose up
docker compose down

これは以下のコマンドに相当するようだ。毎回実行するのは少々大変。

コマンド
docker build . -t docker5-4
docker run -dit --name mynginx --rm -p 8080:80 docker5-4

また、複数のサービスと連携させるときにもdocker-composeが役に立つようだ。生成AIによるとここから、Node.js+Express/Flaskの環境を作ったり、MySQL+SNSサイトのような例を簡単に作成できるらしい。この本が終わったら、試しにいくつか出力させてみよう。または、復習編でApacheで同様なことを行うdocker5-4-1を作っても良いかも。

あと少しでこの本も終了だ。もう一息頑張ろう。

次の記事

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?