본문 바로가기

Devops/Docker

[Docker] ssh 가능한 Ubuntu 컨테이너 만들기

Docker 환경에서 Devops 환경을 만들기 위해서는 Jenkins, Gitlab 이외에 최종 빌드 Artifact를 받을수 있는 Virtual Server가 필요하다. Docker 를 이용해 위 컨테이너를 만들어 본다.

 

로컬에 .pem키 준비

ssh-keygen -t rsa -b 4096 -f mykey.pem
chmod 400 mykey.pem

#mykey.pem → 개인키
#mykey.pem.pub → 공개키

mkdir ssh
cp mykey.pem.pub ssh/authorized_keys

 

Dockerfile 생성 (ubuntu 사용자 생성 및 sudo 권한 부여 with no password, openjdk-17)

FROM ubuntu:22.04

RUN apt-get update && \
    apt-get install -y openssh-server sudo openjdk-17-jdk && \
    mkdir /var/run/sshd && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

# 일반 사용자 생성
RUN useradd -m -s /bin/bash ubuntu && \
    usermod -aG sudo ubuntu && \
    echo "ubuntu ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/ubuntu && \
    chmod 440 /etc/sudoers.d/ubuntu

# SSH 보안 설정 (키 기반)
RUN sed -i 's/#PubkeyAuthentication yes/PubkeyAuthentication yes/' /etc/ssh/sshd_config && \
    sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config && \
    sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin no/' /etc/ssh/sshd_config

# JAVA_HOME 설정
ENV JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64
ENV PATH=$JAVA_HOME/bin:$PATH

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

 

Docker Build

docker build -t ubuntu-ssh .

[+] Building 34.6s (8/8) FINISHED                                                                                                              docker:default
 => [internal] load build definition from Dockerfile                                                                                                     0.0s
 => => transferring dockerfile: 656B                                                                                                                     0.0s
 => [internal] load metadata for docker.io/library/ubuntu:22.04                                                                                          0.0s
 => [internal] load .dockerignore                                                                                                                        0.0s
 => => transferring context: 2B                                                                                                                          0.0s
 => CACHED [1/4] FROM docker.io/library/ubuntu:22.04                                                                                                     0.0s
 => [2/4] RUN apt-get update &&     apt-get install -y openssh-server sudo &&     mkdir /var/run/sshd                                                   32.6s
 => [3/4] RUN useradd -m -s /bin/bash ubuntu &&     usermod -aG sudo ubuntu &&     echo "ubuntu ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/ubuntu &&       0.6s
 => [4/4] RUN sed -i 's/#PubkeyAuthentication yes/PubkeyAuthentication yes/' /etc/ssh/sshd_config &&     sed -i 's/#PasswordAuthentication yes/Password  0.5s
 => exporting to image                                                                                                                                   0.8s
 => => exporting layers                                                                                                                                  0.7s
 => => writing image sha256:7dfc73e705afbef8a3488034cac6eaa684d5760e5b969111d4e3953a6b73da56                                                             0.0s
 => => naming to docker.io/library/ubuntu-ssh

 

Docker Run

- docker run에서 -v는 “볼륨(volume) 마운트 옵션” 

- 왜 -v를 쓰나요?

✅ 1. 컨테이너 재생성해도 키 유지

  • 컨테이너 삭제 후 다시 띄워도 호스트의 authorized_keys를 그대로 사용 가능

✅ 2. 이미지 안에 키를 넣지 않아 보안상 안전

  • Dockerfile에 키를 COPY ❌
  • 호스트에서만 관리 ⭕

✅ 3. 키 변경 즉시 반영

docker run -d \
  --name ubuntu-ssh \
  -p 2222:22 \
  -v $(pwd)/ssh/authorized_keys:/home/ubuntu/.ssh/authorized_keys \
  ubuntu-ssh

 

권한 설정

docker exec ubuntu-ssh bash -c "
  mkdir -p /home/ubuntu/.ssh &&
  chmod 700 /home/ubuntu/.ssh &&
  chmod 600 /home/ubuntu/.ssh/authorized_keys &&
  chown -R ubuntu:ubuntu /home/ubuntu/.ssh
"

 

접속 테스트

root@Kindlove:/home/kindlove/temp/Dockerfile# ssh -i ../pemKey/mykey.pem ubuntu@localhost -p 2222
The authenticity of host '[localhost]:2222 ([127.0.0.1]:2222)' can't be established.
ED25519 key fingerprint is SHA256:5yNtSke6bBPGUDx7SR5NMV+qiVxHfN8tgxDFqam59HM.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '[localhost]:2222' (ED25519) to the list of known hosts.
Welcome to Ubuntu 22.04.5 LTS (GNU/Linux 6.6.87.2-microsoft-standard-WSL2 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 <command>".
See "man sudo_root" for details.

ubuntu@1116ab7e326a:~$ sudo su
root@1116ab7e326a:/home/ubuntu#

 

만일 접속 정보가 달라져서 아래와 같이 에러가 나오면 다음과 같이 해결

# 접속 client IP 변경 등으로 정보가 변경되어 아래 에러가 발생하면 다음과 같이 조치

root@Kindlove:/home/kindlove/temp/Dockerfile# ssh -i ../pemKey/mykey.pem ubuntu@localhost -p 2222
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that a host key has just been changed.
The fingerprint for the ED25519 key sent by the remote host is
SHA256:wNPOTR0VOc0GhkamJpvWGAvWucim35xfZsVvuIaHT90.
Please contact your system administrator.
Add correct host key in /root/.ssh/known_hosts to get rid of this message.
Offending ECDSA key in /root/.ssh/known_hosts:12
  remove with:
  ssh-keygen -f "/root/.ssh/known_hosts" -R "[localhost]:2222"
Host key for [localhost]:2222 has changed and you have requested strict checking.
Host key verification failed.
root@Kindlove:/home/kindlove/temp/Dockerfile# ssh-keygen -R "[localhost\]:2222"
Host [localhost\\]:2222 not found in /root/.ssh/known_hosts
root@Kindlove:/home/kindlove/temp/Dockerfile#
root@Kindlove:/home/kindlove/temp/Dockerfile# ssh-keygen -R "[localhost]:2222"
# Host [localhost]:2222 found: line 10
# Host [localhost]:2222 found: line 11
# Host [localhost]:2222 found: line 12
/root/.ssh/known_hosts updated.
Original contents retained as /root/.ssh/known_hosts.old

# 접속확인

root@Kindlove:/home/kindlove/temp/Dockerfile# ssh -i ../pemKey/mykey.pem ubuntu@localhost -p 2222
Welcome to Ubuntu 22.04.5 LTS (GNU/Linux 6.6.87.2-microsoft-standard-WSL2 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.
Last login: Tue Jan  6 04:40:07 2026 from 172.17.0.1

 

-- The End