LoginSignup
22
14

More than 1 year has passed since last update.

Docker | 公開鍵でコンテナにssh接続する出来るようにするDockerfileの例

Last updated at Posted at 2017-10-03

解説

dockerだからといって特別なことをするわけではない。
サーバー側でssh接続できる設定などをおこない、公開鍵を設置する。

動作例 ( Ubuntu の場合 )

Dockerfile

Dockerfile
FROM ubuntu:16.04

RUN apt-get update && apt-get install -y openssh-server
RUN mkdir /var/run/sshd

# ssh設定ファイルの書換え
RUN sed -i 's/PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
RUN sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config

# SSH login fix. Otherwise user is kicked off after login
RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd

ENV NOTVISIBLE "in users profile"
RUN echo "export VISIBLE=now" >> /etc/profile

# 手元の公開鍵をコピー
COPY id_rsa.pub /root/authorized_keys

# ssh用の port を晒す
EXPOSE 22

# 公開鍵を使えるようにする (パーミッション変更など)
CMD mkdir ~/.ssh && \
    mv ~/authorized_keys ~/.ssh/authorized_keys && \
    chmod 0600 ~/.ssh/authorized_keys &&  \
    # 最後に ssh を起動
    /usr/sbin/sshd -D

手元に鍵のペアを作っておく

$ ssh-keygen -f ./id_rsa -t rsa -b 4096 -C 'example@com' -N ''

イメージをビルド

上記 DockerfileCOPY 指定により、公開鍵がイメージにコピーされる。

$ docker image build . -t ssh_server

コンテナを走らせる

$ docker run -d -p 10000:22 ssh_server

秘密鍵を指定してsshログインする

$ ssh root@127.0.0.1 -p 10000 -i id_rsa

環境

  • Docker for mac
  • Docker version 17.06.1-ce, build 874a737

リンク

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

22
14
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
22
14