Deploy a Docker container with SSH access
Prepare Dockerfile, image, container and IP address
- Dockerfile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
FROM ubuntu:22.10
RUN apt update && apt install -y openssh-server nano
RUN mkdir /var/run/sshd
# Aa@123456 is root password
RUN echo 'root:Aa@123456' | 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
EXPOSE 22
CMD ["/usr/sbin/sshd", "-D"]
- Build the image and deploy the container
1
2
docker build -t sshd_ubuntu .
docker run -d -P --name test_sshd sshd_ubuntu
- Locate the IP address of the running container
1
2
3
docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' test_sshd
// ex output: 172.17.0.2
SSH into the running container (using password)
- Tune SSH Daemon Configuration
1
2
3
// docker exec -it <container_id> bash
docker exec -it test_sshd bash
nano /etc/ssh/sshd_config
- In that file (sshd_config), uncomment the line:
1
#PermitRootLogin yes
- That line should look like this:
1
PermitRootLogin yes
- Restart the SSH daemon:
1
2
service ssh restart
docker restart test_sshd
- SSH into the container
Using the root’s password: Aa@123456
1
2
// ssh root@IP
ssh [email protected]
SSH into the running container (using SSH key)
- Create a RSA Key Pair
1
ssh-keygen -t rsa
- Add id_rsa.pub to remote server (docker container)
1
cat ~/.ssh/id_rsa.pub | ssh [email protected] "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys"
References
This post is licensed under CC BY 4.0 by the author.