[ubuntu] SSH login to docker

Time:2022-6-10

Method 1

If the SSH service has been set for the image, you can:

docker run -d your_image:tag /usr/sbin/sshd -p 12345 -D
  • -dIt is the instruction of docker and runs in the background
  • /usr/sbin/sshd -p 12345 -DThe command that the container runs to open the SSH connection of port 12345

-Interpretation of D
Do not detach and become daemon. This is often used when sshd is run using systemd. This allows easier monitoring of the process in such environments. Without this option, the SSH server forks and detaches from terminal, making itself a background daemon process. The latter has been the traditional way to run the SSH server until recently. Many embedded systems would still use the latter.

When connecting in other places, the password is the original host password by default. You can modify it according to method 2

$ ssh [email protected]{ip got above} -p 12345

Method II

After entering the container, firstChange apt source

# install ssh
$ apt-get install openssh-client
$ apt-get install openssh-server -y

# start ssh service
$ /etc/init.d/ssh start
 * Starting OpenBSD Secure Shell server sshd        [ OK ] 

# enable root login
$ vim /etc/ssh/sshd_config

#------------ in file sshd_config -------------#
# "PermitRootLogin yes" needs adding as below
#Add "permitrootlogin yes" as follows
...
#LoginGraceTime 2m
#PermitRootLogin prohibit-password
PermitRootLogin yes
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10
...
#---------- end of file sshd_config -----------#

# restart service
$ service ssh restart
* Restarting OpenBSD Secure Shell server sshd            [ OK ] 


# set password of user root
$ passwd root

# add port to ssh
$ /usr/sbin/sshd -p 12345

# checkout ip
$ apt-get install net-tools
$ ifconfig

Connect elsewhere

$ ssh [email protected]{ip got above} -p 12345