【Docker】パスワード認証つきでSSH接続ができるdockerコンテナを作成する

DockerでSSHができるコンテナの作成を行う記事はたくさん見つかるのですが、パスワード認証でSSH接続ができるようにする記事は少なかったので書きます。

ubuntuのDockerfile

SSHをされる側はubuntu:latestで行います。 内容としてはopenssh-serverをインストールして、パスワードを変更したのち設定を変更してsshdを起動しているだけ。ubuntuコンテナのrootのパスワードがYOUR_PASSWORDになります。

FROM ubuntu:latest

RUN apt-get update && apt-get install -y openssh-server
RUN mkdir /var/run/sshd
RUN echo 'root:YOUR_PASSWORD' | chpasswd
RUN sed -i 's/#PasswordAuthentication yes/PasswordAuthentication yes/g' /etc/ssh/sshd_config
RUN sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config

EXPOSE 22
CMD ["/usr/sbin/sshd", "-D"]

docker buildコマンドを使ってもいいのですが、面倒なのでdocker composeを用います。ホストOSの22番はすでに埋まってると思うので2222番にコンテナの22番を設定します。

version: "3"
services:
  server:
    build: ./ubuntu
    restart: always
    ports:
      - "2222:22"

ディレクトリ全体は以下の通り。

$ tree               
├── compose.yml
└── ubuntu
   └── Dockerfile

いざ接続

以下のコマンドを用いて接続できます。

❯ ssh root@127.0.0.1 -p 2222
root@127.0.0.1\'s password: 

Welcomeが表示されて無事SSH接続が確認できました!

Welcome to Ubuntu 22.04.3 LTS (GNU/Linux 5.15.49-linuxkit)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

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.
Last login: Tue Dec 19 15:49:22 2023 from 172.24.0.1
root@0621f159dd82:~# 

おしまい