openssh-server doesn't start in Docker container

10,144

Solution 1

Container vs. Image

The RUN statement is used to run commands when building the docker image.
With ENTRYPOINT and CMD you can define what to run when you start a container using that image.
See Dockerfile Reference for explanations how to use them.

Services

There is not preinstalled init-system in the containers, so you cannot use service ... start in a container.
Consider starting the process in the CMD statement as foreground process or use an init-system like Phusion or Supervisord.

Solution 2

In my opinion there is a better approach:

Dockerfile

FROM ubuntu:14.04.1
EXPOSE 22
COPY docker-entrypoint.sh /docker-entrypoint.sh
RUN chmod +x /docker-entrypoint.sh
RUN apt-get install -y openssh-server

ENTRYPOINT ["sh", "/docker-entrypoint.sh"]

# THIS PART WILL BE REPLACED IF YOU PASS SOME OTHER COMMAND TO docker RUN
CMD while true; do echo "default arg" && sleep 1; done

docker-entrypoint.sh

#!/bin/bash
service ssh restart
exec "$@"

Build command docker build -t sshtest .

The benefit of this approach is that your ssh daemon will always start when you use docker run, but you can also specify optional arguments e.g.:

docker run sshtest will print default arg every 1 second whether docker run sshtest sh -c 'while true; do echo "passed arg" && sleep 3; done' will print passed arg every 3 seconds

Share:
10,144

Related videos on Youtube

Admin
Author by

Admin

Updated on September 18, 2022

Comments

  • Admin
    Admin over 1 year

    I am having a weird problem.

    I am not able to ssh to docker container having ip address 172.17.0.61.

    I am getting following error:

    $ ssh 172.17.0.61
    ssh: connect to host 172.17.0.61 port 22: Connection refused
    

    My Dockerfile does contain openssh-server installation step:

    RUN apt-get -y install curl runit openssh-server
    

    And also step to start ssh:

    RUN service ssh start
    

    What could be the issue?

    When I enter into container using nsenter and start ssh service then I am able to ssh. But while creating container ssh-server doesn't seems to start.

    What should I do?