Thursday, November 26, 2020

Setting up SSH on a Custom Linux Docker Container

I had some Azure App Services for Containers and when I wanted to SSH, it was giving this annoying error: SSH CONNECTION CLOSE - Error: connect ECONNREFUSED <ipaddress>:2222.

SSH CONNECTION CLOSE - Error: connect ECONNREFUSED

In this post let's see how we can set up SSH on a Custom Linux Docker Container and get past this error. It's actually pretty easy, there is official documentation: Configure SSH in a custom container. I feel it's not that intuitive, hence this post.

First, you need to install openssh-server inside your docker image, I happen to be using aspnet:3.1-buster-slim as the base in my case. It shouldn't matter.
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base

RUN apt-get update -y \
    && apt-get install -y --no-install-recommends openssh-server 
Now you need to set a password for the root account.
RUN mkdir -p /run/sshd && echo "root:Docker!" | chpasswd
Then you need to add this sshd_config file inside /etc/ssh in the image.
# This is ssh server systemwide configuration file.
#
# /etc/sshd_config

Port                 2222
ListenAddress  0.0.0.0
LoginGraceTime  180
X11Forwarding  yes
Ciphers aes128-cbc,3des-cbc,aes256-cbc,aes128-ctr,aes192-ctr,aes256-ctr
MACs hmac-sha1,hmac-sha1-96
StrictModes  yes
SyslogFacility  DAEMON
PasswordAuthentication  yes
PermitEmptyPasswords  no
PermitRootLogin  yes
Subsystem sftp internal-sftp

You can copy the file as below,
COPY sshd_config /etc/ssh/
In sshd_config, SSH port is 2222, so we need to expose it.
EXPOSE 2222
We are almost there now. The final step is to start the SSH server (here, I am just running 2 commands, in my case I needed to run a .NET application as well).
ENTRYPOINT ["/bin/bash""-c""/usr/sbin/sshd && dotnet SomeApplication.dll"]
And now when this container is running, you should be able to SSH into it.
SSH

SSH Connection Established
Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment