Docker Image

認識 Dockerfile

  • Dockerfile 就是建置 Docker Image 的腳本

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

自製 Alpine OpenSSH Server 的 Docker Image

撰寫 alpine.plus Dockerfile

$ cd ~/wulin; mkdir plus
$ nano plus/Dockerfile
FROM alpine.base
RUN apk update &&
apk add no-cache openssh-server tzdata &&
# 設定時區
cp /usr/share/zoneinfo/Asia/Taipei /etc/localtime &&
ssh-keygen -t rsa -P "" -f /etc/ssh/ssh_host_rsa_key &&
echo -e 'Welcome to Alpine 3.11.6\n' > /etc/motd && \
# 建立管理者帳號 bigred
adduser -s /bin/bash -h /home/bigred -G wheel -D bigred && echo '%wheel ALL=(ALL) NOPASSWD: ALL' >> /etc/sudoers &&
echo -e "bigred\nbigred\n" | passwd bigred &>/dev/null && [ "$?" == "0" ] && echo "bigred ok"

EXPOSE 22

ENTRYPOINT ["/usr/sbin/sshd"]
CMD ["-D"]

[重要] ENTRYPOINT 所指定的執行命令, 在建立 Container 時強制執行此命令並且不可被其它命令取代

建立與使用 alpine.plus image

$ docker build no-cache -t alpine.plus plus/

$ docker run rm name s1 -h s1 alpine.plus sh
Extra argument sh.

[重要] 因使用 entrypoint 宣告內定命令, 便無法自行指定執行命令

建立 s1 container

$ docker run rm name s1 -h s1 -d -p 22100:22 alpine.plus

登入 s1 貨櫃主機
$ ssh puxxxx@localhost -p 22100
puxxxx@140.128.xx.xx's password: xxxxx

$ ps aux

$ sudo kill -9 1
sudo: setrlimit(RLIMIT_CORE): Operation not permitted

$ exit

$ docker stop s1


$ docker ps -a

$ docker rm -f s1

$ network rm mynet

$ network create mynetxx

$ nano network

(8 9 改成自己要的不能和別人重疊)

$ docker run rm name s2021 -net=mynetxx -d -p 22100:22 astich/alpine.plus

$ docker exec -it s2021 sh

/# ifconfig

不能用 bigred 登入, 令建立帳號個別, 就無須 sudo 權限

$ docker exec s01 useradd -m -s /bin/bash s01

$ docker exec -it s01 sh

/# passwd s01

(不用一直做 images)

Docker Image 備份與還原

Docker Image 備份

$ cd ~/wk/wulin

$ docker history alpine.plus

  • 備份 Image
    $ docker save alpine.plus > alpine.plus.tar

Docker Image 還原

  • 還原 Image
    $ docker rmi alpine.plus

$ docker load < alpine.plus.tar

$ docker history alpine.plus

[重點] 還原的 image 的目錄架構, 與原先 Image目錄架構一樣

Docker Container 備份與還原

$ docker run name s2 -h s2 -d alpine.plus
6e52bd5aee18c0aed8dbb17920037be0b9109158329b401c56b4f64417c2d784

[重要] 使用上述命令建立 s2 Container, 這個 Container 有啟動 openssh server, 所以這個 Container 有 openssh 的執行狀態資訊檔, 這時使用 docker export 命令
匯出的 Tar 檔中就會有殘留 openssh 的執行暫存檔, 以至後續做出的 image 無法啟動 openssh server, 所以必須先關閉 s2 container, 才可備份此 container

$ docker stop s2
$ docker export s2 > s2.tar

$ docker rm s2 && docker rmi alpine.plus
$ cat s2.tar | docker import - alpine.plus &>/dev/null

$ docker history alpine.plus

使用重製 alpine.plus image

$ docker run name s2 -h s2 -d alpine.plus
docker: Error response from daemon: No command specified.
See 'docker run help'.

[重要] 重製後的 alpine.plus image 必須指定 執行命令

$ docker run name s2 -h s2 -d alpine.plus /usr/sbin/sshd -D

$ docker ps -a

$ docker rm -f s2