2025/05/06 Updated by

Docker Image を自作する

最も簡単な例


[Up] Japanese English

ubuntu24.04LTS をベースとし、新規ユーザを作成する

方針

作成手順

  1. 作業用フォルダを作成する。
  2.   $ mkdir -p ~/doc/docker/ubuntu24_user
      $ cd ~/doc/docker/ubuntu24_user
    
  3. 作業用フォルダの中に Dockerfile を作成する。
  4. Dockerfile
    # ゲストOS: Ubuntu 24.04 LTS
    
    FROM ubuntu:24.04
    
    
    # Change Your Own UNAME, UID, GID, PASS
    
    ENV UNAME=guest
    ENV UID=3000
    ENV GID=3000
    ENV PASS=パスワード
    
    ENV SSHD_PORT=22
    
    # 必要なパッケージのインストール
    
    RUN apt-get update && \
        DEBIAN_FRONTEND=noninteractive apt-get install -y \
        sudo \
        bash \
        && rm -rf /var/lib/apt/lists/*
    
    
    # Copy Shell Script "entrypoint.sh"
    
    COPY entrypoint.sh /entrypoint.sh
    RUN chmod +x /entrypoint.sh
    
    ENTRYPOINT ["/entrypoint.sh"]
    
    CMD []
    
  5. 作業用フォルダの中に entrypoint.sh を作成する。
  6. entrypoint.sh
    #!/bin/bash
    set -e
    
    if [ ! -f /var/app/.initialized ]; then
        ######## First Time ########
    
        echo "First run. Setting up ..."
        mkdir -p /var/app
        touch /var/app/.initialized
    
        # ユーザーが存在しない場合のみ作成する
        if id "${UNAME}" &>/dev/null; then
            echo "User ${UNAME} already exists. Skipping creation."
        else
            # 同名グループが無ければ作成
            if ! getent group "${UNAME}" &>/dev/null; then
                echo "Creating group ${UNAME} with GID=${GID}"
                groupadd -g ${GID} ${UNAME}
            else
                echo "Group ${UNAME} already exists. Skipping group creation."
            fi
        
            echo "Creating user ${UNAME} with UID=${UID}, GID=${GID}"
            useradd -m -u ${UID} -g ${GID} -s /bin/bash ${UNAME}
            echo "${UNAME}:${PASS}" | chpasswd
            usermod -aG sudo ${UNAME}
        fi
    
        # ホームディレクトリの Owner が root:root になることがあるので変更する。
        chown -v ${UNAME}:${UNAME}  /home/${UNAME}
    
    else
        ######## Second Time or Later ########
        
        echo "Starting for the second time or later ..."
    
    fi
    
    
    # Execute Commands in CMD
    
    if [ "$#" -gt 0 ]; then
        exec "$@"
    else
        echo "No command provided. Starting bash ..."
        exec bash
    fi
    
  7. Image を build する。
  8.   $ docker build -t ubuntu24-user .
      ...
    成功
    
  9. 生成した Image を確認する
  10. $ docker image ls
    REPOSITORY      TAG       IMAGE ID       CREATED          SIZE
    ubuntu24-user   latest    ac92161948dc   21 seconds ago   126MB
    ...
    

Container 用の永続的なファイルシステムを作成する

コンテナに永続的なファイルシステムを提供するために、1777 のパーミッションでフォルダを作っておく。 skicky bit が on (1777) のフォルダには、 「誰でもファイルを作成できるが、作成した本人だけがファイルを変更したり消したりできる」 という特徴がある。

$ sudo mkdir -p /home/docker         ← ディレクトリを作成する
$ sudo chmod 1777 /home/docker       ← 誰でもファイルを作成できるが、作成した本人にしか消去できないモードに設定する
$ ls -ld /home/docker                ← ディレクトリのsticky bit が on になっていることを確認する。
drwxrwxrwt 3 root root 4096  5月 06 17:57 /home/docker

Docker Contaner を生成する (1)

Image ubuntu24-user のデフォルトのユーザ情報を用いて、新しい Container ubuntu24-guest を生成する。

  1. Image から Container を生成して起動する。ユーザ情報はデフォルト値 (guest) を利用する。 Container のファイルシステム内にホストOSのディレクトリをマウントする。
  2. $ docker run --name ubuntu24-guest \
        -v /home/docker/guest:/mnt/hostos \
        -it ubuntu24-user
    
    起動オプション
  3. Container を起動した対話環境が、そのまま Container 内で動作する bash との対話環境になる。
  4. First run. Setting up ...                                                 ←(Conainer内の対話環境)
    Creating group guest with GID=3000
    Creating user guest with UID=3000, GID=3000
    ownership of '/home/guest' retained as guest:guest
    No command provided. Starting bash ...
    #              ← Container 内の対話環境 (root権限の bash) が動く
    
  5. (Container 内で) Container 内の対話環境を調べる。
  6. # whoami
    root                                       ← root権限で動作している
    # pwd
    /                                          ← カレントディレクトリは '/'
    # ls -ld /mnt/hostos
    drwxr-xr-x 2 root root 4096 May  6 09:29 /mnt/hostos         ← ホストOSをマウントしたディレクトリ
    
  7. (Container 内で) Container の状況を調べる。
  8. # ls -ld /home/guest
    drwxr-x--- 2 guest guest 4096 May  6 14:06 /home/guest
    # ls -la /home/guest
    total 20
    drwxr-x--- 2 guest guest 4096 May  6 14:06 .
    drwxr-xr-x 1 root  root  4096 May  6 14:06 ..
    -rw-r--r-- 1 guest guest  220 Mar 31  2024 .bash_logout
    -rw-r--r-- 1 guest guest 3771 Mar 31  2024 .bashrc
    -rw-r--r-- 1 guest guest  807 Mar 31  2024 .profile
    
  9. (Container 内で) Container 内に作成したユーザの状況を調べる。
  10. # grep guest /etc/group
    sudo:x:27:ubuntu,guest                         ← sudo グループにも追加されている
    guest:x:3000:                                  ← グループID
    # grep guest /etc/passwd
    guest:x:3000:3000::/home/guest:/bin/bash       ← ユーザIDなど
    # ls -ld /home/guest
    drwxr-x--- 2 guest guest 4096 May  6 14:06 /home/guest         ← ホームディレクトリのパーミッション
    # ls -la /home/guest
    total 20
    drwxr-x--- 2 guest guest 4096 May  6 14:06 .
    drwxr-xr-x 1 root  root  4096 May  6 14:06 ..
    -rw-r--r-- 1 guest guest  220 Mar 31  2024 .bash_logout         ← ホームディレクトリに自動で追加されたファイル群
    -rw-r--r-- 1 guest guest 3771 Mar 31  2024 .bashrc
    -rw-r--r-- 1 guest guest  807 Mar 31  2024 .profile
    
  11. (Container 内で) Control-P + Control-Q を入するtことで、Container 内の対話環境から抜けて、ホストOSの対話環境に戻る。
  12. ここで^C (Control-C) などを入力して Container の対話環境を終了すると Container 自体の実行が終了してしまうので注意。

    # ^P ^Q                              ← 'Control-P' + 'Control-Q' で Container を detatch する。
    
    $            ← ホストOSの対話環境に戻る
    
  13. Container からマウントされるホスト OS の /home/docker/guest が存在しない場合は作成されている。 ホストOSにおけるファイルの権限は "docker run" を実行したホストOSのユーザ (nitta) の場合と、root の場合があるようだ(システムの設定状況依存)。
  14. $ ls -ld /home/docker/guest
    drwxr-xr-x 2 nitta nitta 4096  5月  2 16:28 /home/docker/guest
    
    $ ls -ld /home/docker/guest
    drwxr-xr-x 2 root root 4096  5月  6 18:29 /home/docker/guest
    
  15. 起動した Container の様子を調べる。
  16. $ docker container ls
    CONTAINER ID   IMAGE           COMMAND            CREATED         STATUS         PORTS     NAMES
    158d183c43e3   ubuntu24-user   "/entrypoint.sh"   6 seconds ago   Up 2 minutes             ubuntu24-guest
    
  17. Container のログを調べる。
  18. $ docker logs ubuntu24-guest
    First run. Setting up ...
    Creating group guest with GID=3000
    Creating user guest with UID=3000, GID=3000
    ownership of '/home/guest' retained as guest:guest
    No command provided. Starting bash ...
    root@3cac23972a28:/# whoami                         ← Container の対話環境の入出力はログに残っている
    root
    ...
    
  19. ホストOSのシェルを、Container の シェルに attachする。
  20. $ docker attach ubuntu24-guest
    # ← Container内のroot権限の対話環境にアクセスする
  21. (Container内で) 追加したユーザにloginする。
  22. # whoami
    root                               ← まだroot権限だけど
    # login guestguest として login する
    Password:           ← guest のパスワードを入力する(エコーバックされない)
    Welcome to Ubuntu 24.04.2 LTS (GNU/Linux 6.11.0-25-generic x86_64)
    ...
    $ guest 権限の対話環境となる
    
  23. (Container 内の guest 権限で) ユーザ状態を調べる
  24. $ whoami                   ← ユーザ名を調べる
    guest
    $ pwd                      ← ホームディレクトリのパスを表示する。
    /home/guest
    
  25. (Container 内の guest 権限で) パスワードを変更する
  26. $ passwd
    Changing password for guest.
    Current password: パスワード ← エコーバックされない
    New password:  新しいパスワード ← エコーバックされない
    Retype new password:  新しパスワード ← エコーバックされない
    passwd: password updated successfully
    
  27. (Container 内の guest 権限で) 途中でホストOSに戻ることもできる
  28. $ ^P ^Q
    
    $       ← ホストOSの対話環境
    
  29. ホストOSから Container に attach すると、先ほどの続きとなる。
  30. $ docker attach ubuntu24-guest
    
    $       ← Containerのguest権限の対話環境
    
  31. guest ユーザのシェルを終わるには、exit
  32. $  exit  ← guest権限
    #       ← Containerのroot権限の対話環境
    
  33. (Container内で) root権限の対話環境を終了すると、Containerの実行も終了する。
  34. $ exit
    Connection to localhost closed.
    
    $       ← ホストOSの対話環境
    
  35. docker の状態を調べる。
  36. 実行中の Container の一覧には ubuntu24-guest 無いことがわかる。
    $ docker container ls
    CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
    
    停止中の Container の一覧には存在する。
    $ docker container ls -a
    CONTAINER ID   IMAGE           COMMAND            CREATED       STATUS                     PORTS     NAMES
    3cac23972a28   ubuntu24-user   "/entrypoint.sh"   3 hours ago   Exited (0) 7 seconds ago             ubuntu24-guest
    
    Image はそのまま存在している。
    $ docker image ls
    REPOSITORY      TAG       IMAGE ID       CREATED       SIZE
    ubuntu24-user   latest    758568c4f956   3 hours ago   81.4MB
    
    

Docker Contaner を生成する (2)

Image ubuntu24-user を用いて、 ユーザ情報を指定して新しい Container ubuntu24-nitta を生成する。

  1. Image から Container を生成して起動する。下に示すのはユーザ名を nitta とした例である。
  2. nitta@um580:~$ docker image ls
    REPOSITORY      TAG       IMAGE ID       CREATED        SIZE
    ubuntu24-user   latest    758568c4f956   17 hours ago   81.4MB
    nitta@um580:~$ docker run --name ubuntu24-nitta -e UNAME=nitta -e UID=2000 -e GID=2000 -e PASS=password -v /home/docker/nitta:/mnt/hostos -it ubuntu24-user
    First run. Setting up ...
    Creating group nitta with GID=2000
    Creating user nitta with UID=2000, GID=2000
    ownership of '/home/nitta' retained as nitta:nitta
    No command provided. Starting bash ...
    root@c45866de1d5d:/# ls -ld /mnt/hostos
    drwxr-xr-x 2 root root 4096 May  7 06:37 /mnt/hostos
    root@c45866de1d5d:/# ls -ld /home/nitta
    drwxr-x--- 2 nitta nitta 4096 May  7 06:37 /home/nitta
    root@c45866de1d5d:/# ls -la /home/nitta
    total 20
    drwxr-x--- 2 nitta nitta 4096 May  7 06:37 .
    drwxr-xr-x 1 root  root  4096 May  7 06:37 ..
    -rw-r--r-- 1 nitta nitta  220 Mar 31  2024 .bash_logout
    -rw-r--r-- 1 nitta nitta 3771 Mar 31  2024 .bashrc
    -rw-r--r-- 1 nitta nitta  807 Mar 31  2024 .profile
    root@c45866de1d5d:/# login nitta
    Password:
    Welcome to Ubuntu 24.04.2 LTS (GNU/Linux 6.11.0-25-generic x86_64)
    
     * Documentation:  https://help.ubuntu.com
     * Management:     https://landscape.canonical.com
     * Support:        https://ubuntu.com/pro
    
    This system has been minimized by removing packages and content that are
    not required on a system that users do not log into.
    
    To restore this content, you can run the 'unminimize' command.
    
    The programs included with the Ubuntu system are free software;
    the exact distribution terms for each program are described in the
    individual files in /usr/share/doc/*/copyright.
    
    Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
    applicable law.
    
    To run a command as administrator (user "root"), use "sudo ".
    See "man sudo_root" for details.
    
    nitta@c45866de1d5d:~$ passwd
    Changing password for nitta.
    Current password:
    New password:
    Retype new password:
    passwd: password updated successfully
    nitta@c45866de1d5d:~$ ls
    nitta@c45866de1d5d:~$ nitta@um580:~$
    nitta@um580:~$ docker container ls
    CONTAINER ID   IMAGE           COMMAND            CREATED              STATUS              PORTS     NAMES
    c45866de1d5d   ubuntu24-user   "/entrypoint.sh"   About a minute ago   Up About a minute             ubuntu24-nitta
    nitta@um580:~$ ls -ld /home/docker/nitta
    drwxr-xr-x 2 root root 4096  5月  7 15:37 /home/docker/nitta
    nitta@um580:~$ docker container ls -a
    CONTAINER ID   IMAGE           COMMAND            CREATED              STATUS                    PORTS     NAMES
    c45866de1d5d   ubuntu24-user   "/entrypoint.sh"   About a minute ago   Up About a minute                   ubuntu24-nitta
    3cac23972a28   ubuntu24-user   "/entrypoint.sh"   17 hours ago         Exited (0) 14 hours ago             ubuntu24-guest
    nitta@um580:~$
    
    $ docker run --name ubuntu24-nitta \
        -e UNAME=nitta -e UID=2000 -e GID=2000 -e PASS=新しいパスワード \
        -v /home/docker/nitta:/mnt/hostos \
        -it ubuntu24-user
    
    起動オプション
  3. Container からマウントされるホスト OS の /home/docker/geust が存在しない場合は、 "docker run" を実行したホストOSのユーザの権限 (nitta) またはrootで作成される。
  4. $ ls -ld /home/docker/nitta
    drwxr-xr-x 2 nitta nitta 4096  5月  2 16:08 /home/docker/nitta
    
  5. 起動した Container の様子を調べる。
  6. $ docker container ls
    CONTAINER ID   IMAGE           COMMAND            CREATED              STATUS              PORTS                              NAMES
    c8096999e40c   ubuntu24-user   "/entrypoint.sh"   About a minute ago   Up About a minute   22/tcp, 0.0.0.0:12023->12023/tcp   ubuntu24-ssh12023
    ...
    
  7. Container のログを調べる。
  8. $ docker logs ubuntu24-ssh12023
    Creating group nitta with GID=2000
    Creating user nitta with UID=2000, GID=2000
    useradd: warning: the home directory /home/nitta already exists.
    useradd: Not copying any file from skel directory into it.
    info: Adding user `nitta' to group `sudo' ...
    changed ownership of '/home/nitta' from root:root to nitta:nitta
    2025-05-04 14:45:27,712 CRIT Supervisor is running as root.  Privileges were not dropped because no user is specified in the config file.  If you intend to run as root, you can set user=root in the config file to avoid this message.
    2025-05-04 14:45:27,713 INFO supervisord started with pid 37
    2025-05-04 14:45:28,716 INFO spawned: 'sshd' with pid 38
    2025-05-04 14:45:29,719 INFO success: sshd entered RUNNING state, process has stayed up for > than 1 seconds (startsecs)
    
  9. ホストOS から、ssh を用いてゲストOS にアクセスする。
  10. $ ssh -p 12023 nitta@localhost
    nitta@localhost's password: パスワード ← エコーバックされない
    (ゲスト OS のシェルが起動する)
    Welcome to Ubuntu 24.04.2 LTS (GNU/Linux 6.10.14-linuxkit x86_64)
    ...
    Last login: Fri May  2 07:29:20 2025 from 172.17.0.1
    $
    
  11. (ゲストOS上で)ホームディレクトリを調べる。
  12. (ゲストOS上で)
    $ pwd            ← ホームディレクトリのパスを表示する。
    /home/nitta
    $ ls -l          ← ホームディレクトリの情報を表示する。
    total 4
    drwxr-xr-x 2 nitta nitta 4096 May  2 07:28 doc      ← ホストOSの /home/docker/nitta がマウントされている
    
  13. (ゲストOS上で) パスワードを変更する
  14. $ passwd
    Changing password for nitta.
    Current password: パスワード ← エコーバックされない
    New password:  新しいパスワード(長いバージョン) ← エコーバックされない
    Retype new password:  新しパスワード ← エコーバックされない
    passwd: password updated successfully
    
  15. (ゲストOS上で) シェルを終了する。
  16. $ exit
    Connection to localhost closed.
    nitta@um580:~/doc/docker$