Connect to Docker Container via SSH

PowerADM.com / Linux / CentOS / Connect to Docker Container via SSH

Using SSH in a docker container is a bad practice and should be avoided. In most cases, it is recommended to use the docker exec command to get a container shell. But in some cases, you need to connect to the docker container remotely via an interactive SSH session.

We assume that Docker is already installed on your host.

In the simplest case, you can use the docker run command to start an interactive session with a docker container. Start your container with the command:

$ sudo docker run --rm -ti -p 50022:22 ubuntu
  • rm – remove the container after exit
  • t – create a pseudo-TTY (virtual terminal session) with the container
  • i (interactive) – the Linux standard input process will be open even when not in use.

After running this command, you will be taken to the console of your Ubuntu container. Now you need to update packages, install OpenSSH server and editor:

$ apt update && apt install openssh-server && apt install nano

Set the root password that you will use for SSH connection:

$ passwd

Now edit the OpenSSH config file:

$ nano /etc/ssh/sshd_config

Uncomment the line PermitRootLogin = yes to allow SSH login as root.

ssh into docker container

Save the file and start the SSH server:

$ /etc/init.d/ssh start

Now you can connect to your container via SSH from the docker host:

 $ ssh -p 50022 root@127.0.0.1

You can also create a docker file to build a container with OpenSSH installed:

FROM ubuntu:latest
RUN apt update && apt install openssh-server sudo -y
RUN useradd -rm -d /home/ubuntu -s /bin/bash -g root -G sudo -u 1000 test
RUN echo 'test:testpassw1' | chpasswd
RUN service ssh start
EXPOSE 22
CMD ["/usr/sbin/sshd","-D"]

Build the docker image:

$ sudo docker build -t ssh_image_test .

Now run the container:

$ sudo docker run ssh_image_test -p 22:22

To get the IP address of the container, run the command:

$ sudo docker inspect -f "{{ .NetworkSettings.IPAddress }}" ssh_image_test

Now you can ssh into your docker container.

$ ssh test@ip_address
Leave a Reply

Your email address will not be published. Required fields are marked *