Run sshd in Docker container

Viewed 2588

I found this Dockerfile sample here:

// version 1
FROM ubuntu:latest
RUN apt update && apt install ssh  -y
RUN service ssh start
CMD ["/usr/sbin/sshd","-D"]

When I build and run this Dockerfile, it runs an SSH server in the foreground, which is great.

If I use the following Dockerfile though:

// version 2
FROM ubuntu:latest
RUN apt update && apt install ssh -y
RUN service ssh start
# CMD ["/usr/sbin/sshd","-D"] // without this line

And then run the container:

~$ docker run -p 2222:22 -it ssh_server

And try to connect to it from another terminal, it doesn't work. Seemingly this call to sshd is necessary. On the other hand, If I just install SSH in the Dockerfile:

// version 3
FROM ubuntu:latest
RUN apt-get update && apt-get install -y ssh

And run the container like this:

~$ docker run -p 2222:22 -it ssh:test
~$ service ssh start
* Starting OpenBSD Secure Shell server sshd 

Now I'm able to connect to the container. So I wonder: If the line RUN ssh service start in version 1 is necessary, why isn't necessary for version 3?

To add more to the confusion, if I build and run version 4:

// version 4
FROM ubuntu:latest
RUN apt update && apt install ssh  -y
#RUN service ssh start // without this line
CMD ["/usr/sbin/sshd","-D"] 

It also doesn't work either.

Can someone please explain those behaviours? What is the relation between service ssh start and /usr/sbin/sshd?

3 Answers

OK everything is clear now:

Basically running the /usr/sbin/sshd is what runs the ssh server. The reason it didn't work out on it's own (version 4) is because the script that runs when you run service ssh start - which is the script /etc/init.d/ssh - creates a directory /run/sshd which is required for the run of sshd.

This script also calls the executable /usr/sbin/sshd, but since this is run as part of the build, it didn't sustain beyond the temporary container that the layer was made of. W

What did sustain is the /run/sshd directory! That's why when we run /usr/sbin/sshd as the CMD it works!

Thanks all!

To build on @YoavKlein's answer, service ssh start can take arguments which are passed to sshd, so rather than

# Incidentally creates /run/sshd
RUN service ssh start
# Run the service in the foreground when starting the container
CMD ["/usr/sbin/sshd", "-D"]

you can just do

# Run the service in the foreground when starting the container
CMD ["service", "ssh", "start", "-D"]

which will start the SSH server through service, but run it in the foreground, avoiding having to have a separate RUN to do first time setup.

I have taken the idea from @mark-raymond :)

Following docker run command with the -D flag worked for me!:

docker run -itd -p 2222:22 <dockerImageName:Tag> /usr/sbin/sshd -D
Related