Docker: How to access a container via ssh
Carlos Costa
A brief introduction.
SSH is a cryptographic network protocol for operating network services securely over an unsecured network. The best known example application is for remote login to computer systems by users.
Docker image
# base image
FROM ubuntu:20.04
# install ssh server
RUN apt update && apt install -y openssh-server
# configure sshd
RUN sed -i 's/PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
# create user
RUN useradd -m -s /bin/bash cnc
# set password
RUN echo "cnc:insecure_password" | chpasswd
# define ssh port
EXPOSE 22
# start sshd
ENTRYPOINT service ssh start && bash
Here we have a simple Dockerfile that installs ssh-server and creates a user called cnc with the password insecure_password
. The root user is also enabled to login via ssh.
Now, let’s create our image:
docker build -t cnc-image .
Container
Let’s create our container based on the image we just created:
docker run -dti --name ssh-test cnc-image
And check the ip address:
docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' ssh-test
# 172.17.0.2
Another way to get the ip address is by using the docker exec
command:
docker exec ssh-test hostname -I
# 172.17.0.2
Access container via ssh
Ok, with the ip address we can now access the container via ssh:
ssh cnc@172.17.0.2