LoginSignup
16
15

More than 3 years have passed since last update.

SSH接続できるDockerコンテナを作る

Last updated at Posted at 2020-05-11

AWS Fargate を Bastion として SSH Tunnel とかやりたかったんだけど、当然の事ながら Docker コンテナを SSH できるようにする必要がありました。

Dockerfile

FROM ubuntu:18.04

RUN apt-get update && apt-get install -y openssh-server

RUN mkdir /var/run/sshd

ARG ROOT_PASSWORD
RUN echo root:${ROOT_PASSWORD} | chpasswd

RUN sed -i 's/#\?PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
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

EXPOSE 22

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

コンテナ立ち上げ

# build docker image.
docker build --build-arg ROOT_PASSWORD=password -t ssh_container .

# run docker container
docker run -itd --rm -p 2222:22 --name ssh_container ssh_container

SSH接続

ssh root@localhost -p 2222
password: password

SSH鍵認証したい場合

鍵作る

ssh-keygen -f id_rsa

ls
id_rsa id_rsa.pub

コンテナに公開鍵を突っ込む

上で紹介した Dockerfile の EXPOSE 22 の上辺りに下記を追加してください。パスワードは消しちゃいます。


# 省略...

# ARG ROOT_PASSWORD
# RUN echo root:${ROOT_PASSWORD} | chpasswd

# 省略...

COPY id_rsa.pub /root/authorized_keys

RUN mkdir ~/.ssh && \
    mv ~/authorized_keys ~/.ssh/authorized_keys && \
    chmod 0600 ~/.ssh/authorized_keys

EXPOSE 22

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

接続

同様に build してから SSH の際に秘密鍵を指定するのみです。

ssh root@localhost -i id_rsa

参考

16
15
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
16
15