docker container can't use `service sshd restart`
Asked Answered
I

1

5

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.

Iridectomy answered 9/1, 2017 at 9:43 Comment(0)
D
10

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.

Disyllable answered 9/1, 2017 at 15:59 Comment(2)
Thanks, Mr Lowe. This really helped. and I saw the modification on my question context. Thanks again and i bet you must do a lot this kind of grammar correction daily to your daughter? I am not a native english-speaker, sorry for that.Iridectomy
@Iridectomy I did clean up the post a little bit - just standard procedure around here... didn't mean any offense, to be clear... we have a lot of non-native English speakers, so those of us who are native speakers do our best to help the posts be as readable as they can be.Disyllable

© 2022 - 2024 — McMap. All rights reserved.