Search code examples
dockersshdockerfilesshd

docker container can't use `service sshd restart`


I am trying to build a hadoop Dockerfile.

In the build process, I added:

  && apt install -y openssh-client \
  && apt install -y openssh-server \
  && ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa \
  && cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys \
  && chmod 0600 ~/.ssh/authorized_keys
  && sed -i '/\#AuthorizedKeysFile/ d' /etc/ssh/sshd_config \
  && echo "AuthorizedKeysFile ~/.ssh/authorized_keys" >> /etc/ssh/sshd_config \
  && /etc/init.d/ssh restart

I assumed that when I ran this container:

docker run -it --rm hadoop/tag bash

I would be able to:

ssh localhost

But I got an error:

ssh: connect to host localhost port 22: Connection refused

If I run this manually inside the container:

/etc/init.d/ssh restart
# or this
service ssh restart

Then I can get connected. I am thinking that this means the sshd restart didn't work.

I am using FROM java in the Dockerfile.


Solution

  • The build process only builds an image. Processes that are run at that time (using RUN) are no longer running after the build, and are not started again when a container is launched using the image.

    What you need to do is get sshd to start at container runtime. The simplest way to do that is using an entrypoint script.

    Dockerfile:

    COPY entrypoint.sh /entrypoint.sh
    RUN chmod +x /entrypoint.sh
    
    ENTRYPOINT ["/entrypoint.sh"]
    CMD ["whatever", "your", "command", "is"]
    

    entrypoint.sh:

    #!/bin/sh
    
    # Start the ssh server
    /etc/init.d/ssh restart
    
    # Execute the CMD
    exec "$@"
    

    Rebuild the image using the above, and when you use it to start a container, it should start sshd before running your CMD.

    You can also change the base image you start from to something like Phusion baseimage if you prefer. It makes it easy to start some services like syslogd, sshd, that you may wish the container to have running.